Recommand · November 3, 2021 0

How to write to a text file that is publicly available to other apps on Android device?

If my Android app has a targetSdk of 31, how can I write to a text file that is publicly available outside of my app by other apps, such as the built-in "Files" system app?

Previously I was writing to a file in the device’s public Documents folder using Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but this method is deprecated and when I use it after changing the targetSdk from 28 to 31 I get the error MediaProvider: Permission to access file: /storage/emulated/0/Documents/my_log.txt is denied.

I’m happy to write to my application-specific Documents folder, e.g. /storage/emulated/0/Android/data/, but how can I make this publicly visible/available to the Files app? MediaScannerConnection.scanFile() no longer works for this.

Is there a solution that doesn’t require a user interaction such as a "Save as…" flow?