我尝试在android外部存储中创建文件夹。我尝试了很多例子,但都没有用。我设置了读取和写入外部存储的运行时权限。它适用于Android API 6、7,但不适用于Android Oreo。
File f = new File(Environment.getExternalStorageDirectory(), "MyDir");
if (!f.exists()) {
try {
boolean is_seccess = f.mkdirs();
if (is_seccess) {
Toast.makeText(this, "create", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not create", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
我检查了外部存储是否可用于读取和写入,它返回true。
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
我授予下面的权限,我也授予运行时权限并允许它。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
仅Android Oreo无法正常运行,其他设备运行良好。我的代码有什么问题?
答案 0 :(得分:0)
该应用程序请求READ_EXTERNAL_STORAGE,并且用户授予了该权限。如果应用的目标API级别为25或更低,则系统还同时授予WRITE_EXTERNAL_STORAGE,因为它属于同一STORAGE权限组,并且也已在清单中注册。如果该应用程序针对Android 8.0(API级别26),则系统当时仅授予READ_EXTERNAL_STORAGE;但是,如果应用程序稍后请求WRITE_EXTERNAL_STORAGE
询问运行时权限,如下所示:
private boolean checkAndRequestPermissions() {
int permissionReadStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
int permissionCamera = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
int permissionWriteStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (permissionReadStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (permissionWriteStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions((Activity) this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}