0
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, "content://com.android.externalstorage.documents/tree/downloads");
grantUriPermission(<packagename>, "content://com.android.externalstorage.documents/tree/downloads", Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(Uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
DocumentFile file = pickedDir.createFile(".csv", "xyz.csv");

Above code was working until P. From Android Q onwards, I am facing below issue:

UID XXXXX does not have permission to content://com.android.externalstorage.documents/tree/downloads [user 0]; you could obtain access using ACTION_OPEN_DOCUMENT or related APIs

Manifest already has:

<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />

Version:

minSdkVersion 26
targetSdkVersion 26
compileSdkVersion 26

Any help is appreciated

be_good_do_good
  • 4,311
  • 3
  • 28
  • 42

1 Answers1

2

You can take a look at this: Work in documents and Create a document

If you want to create a new file in the external public directory, you should use the Storage Access Framework to let the user choose the location to save this file. And this file creates by your app, so your app can access it without any storage permission.

The flow look like:

  1. Start an Intent with ACTION_CREATE_DOCUMENT.
  2. User choose the location to save the new file (it will show the default location base on your mimeType in Intent extra)
  3. Get Uri from onActivityResult, then open an OutputStream use resolver.openOutputStream(uri)
  4. Write data to outputStream.
Tuan Nguyen
  • 131
  • 6
  • I do not want user to select a location. I want to hardcode a location as i mentioned – be_good_do_good Aug 20 '19 at 19:33
  • Try to use this: `File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "xyz.csv") file.createNewFile()` – Tuan Nguyen Aug 21 '19 at 03:27