<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xt.client">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
private void writeFile() throws IOException {
String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(absolutePath + File.separator + "a.txt");
if (file.exists()) {
file.delete();
ToastUtil.showCenterToast("文件存在,删除成功");
} else {
file.createNewFile();
ToastUtil.showCenterToast("文件不存在,创建成功");
}
}
if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else{
writeFile();
}
在返回的结果里面进行判断,如果给予了权限,则进行写入操作。
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==1 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
writeFile();
}
}
1.targetSdkVersion<29 的应用程序默认带有requestLegacyExternalStorage=true属性。不需要额外处理。
2.targetSdkVersion>=29,需要在manifest的application中进行申请使用:
<application
android:name=".application.DemoApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
tools:ignore="GoogleAppIndexingWarning">
>
安卓11的时候继续强化对SD卡读写的管理,引入了MANAGE_EXTERNAL_STORAGE权限,而之前的WRITE_EXTERNAL_STORAGE已经失效了。
并且MANAGE_EXTERNAL_STORAGE权限只能跳转设置页面申请。
if (sdkInt >= 30) {
if (!Environment.isExternalStorageManager()) {
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(intent);
return;
}
writeFile();
return;
}
android studio 一般报错日志:java.io.IOException: Operation not permitted
sd卡读写权限问题