有没有一种方法可以将文本文件保存到 public 目录而无需任何针对 Android API 30 的用户交互?

Is there a way to save a text file to a public directory without any user interaction targeting Android API 30?

File fFoo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "foo.txt");
BufferedWriter bos = new BufferedWriter(new FileWriter(fFoo));

以上代码抛出:

java.io.FileNotFoundException: /storage/emulated/0/Download/foo.txt: open failed: EACCES (Permission denied)

在build.gradle中:

compileSdkVersion 31
targetSdkVersion 30

有人可以给点小费吗?

对于 API 29+ 你可以使用 MediaStore API,这是一个例子:

ContentResolver contentResolver = context.getContentResolver();

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
values.put(MediaStore.MediaColumns.IS_PENDING, 1);

Uri mediaUri = contentResolver.insert(
        MediaStore.Downloads.EXTERNAL_CONTENT_URI,
        values);

try (OutputStream out = contentResolver.openOutputStream(mediaUri)){
    // Write your data here
    out.write(data);
}

values = new ContentValues();
values.put(MediaStore.MediaColumns.IS_PENDING, 0);

contentResolver.update(mediaUri, values, null, null);

要将文件放入子文件夹,我们应该在调用 insert() 之前再添加一行

values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/subfolder");

更多信息:https://developer.android.com/training/data-storage/shared/media#add-item