1、在AndroidManifest.xml中添加权限
1、添加读写权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2、在application中添加该句
android:requestLegacyExternalStorage="true"
在application中添加该句(很重要) android:requestLegacyExternalStorage="true"?
2、代码中动态申请权限
private void requestMyPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//没有授权,编写申请权限代码
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
} else {
Log.d(TAG, "requestMyPermissions: 有写SD权限");
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//没有授权,编写申请权限代码
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
} else {
Log.d(TAG, "requestMyPermissions: 有读SD权限");
}
}
|