I am working on a simple app that plays audio files and I would like to be able to open the app from an audio file in, for example, a file browser. The intent filter and all that is set, but I am struggling with how to use what I receive.
the content:// uri I receive doesn't seem to be meant to be used to get to the actual file - I have looked at the answers to the question here: Android: Getting a file URI from a content URI?, but the approach described there to get a file and not just use the inputStream (which is basically what I want) doesn't seem to be the right way, judging from the discouaging comments and also this site: How to Consume Content from a Uri. Or am I mistaken?
Right now, I am calling this method in my MainActivity to handle my intent, which basically just creates a temporary copy of the file and passes it to where it's used:
private fun handleIntent() {
val uri = intent.data
val inputStream = contentResolver.openInputStream(uri)
val outputFile = File(this.cacheDir, "output.wav")
val outputStream = FileOutputStream(outputFile)
inputStream.use { input ->
outputStream.use { output ->
input.copyTo(output)
}
}
DataRepository.handleFileFromIntent(outputFile)
showPlayerFragmentWithFreshSelection()
}
This almost works (as in I get what is passed to the app as a File), but in a wrong way. Since I want to add the file to a selection of audio files my player can go through, and would like to be able to save this selection, saving a temporary file, or even a copy at all is not the right approach here (I just named the file "output.wav" here because I knew for my test I would be using a .wav file)
Is there any proper and safe way to get the actual path to the file from my content uri or is this just something that can't (or shouldn't) be done at all?
I am writing this in Kotlin, but answers using Java are very wellcome too!