I would like to do the following:
- Read and edit a file that is created on the device via USB cable connected to a PC.
- Write files that are visible when the user opens the device's internal storage in the windows file explorer.
I target Android 10 (API level 29).
The best solution I was able to find for reading files was the deprecated
val containerFile = File(
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"myFile.csv"
)
// Then I was able to read files from
val inputStream: InputStream = contentResolver.openInputStream(Uri.fromFile(containerFile))!!
This way when I placed "myFile.csv" in the downloads folder, my app was able to read the contents.
As for creating PC-readable files, the only solution I found was to create hidden temporary files, and whenever I had to make them readable from PC, I created an intent as follows:
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "file/csv"
putExtra(Intent.EXTRA_TITLE, "output.csv")
// I specify a URI for the directory that should be opened in the system file picker
putExtra(
DocumentsContract.EXTRA_INITIAL_URI,
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
)
}
Is there any better solution?
If not, how do I get a path to a directory which is visible from PC, using API 29?
I know this should be possible, since there are many text editor apps for android, which are doing the same things I want to, but I was not able to find any tutorial.
I need a long term solution, I'm very confused...
Thank you very much!
question from:
https://stackoverflow.com/questions/65847442/how-do-i-handle-files-on-android-device-that-are-created-by-a-pc-api-level-29 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…