I download a file using Retrofit and save it in a subfolder in the download directory.
when I check with the phone's file manager, it is downloaded and saved correctly. For example, in the following path: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + "/MyApp"
But when I open the file manager with intent like ACTION_GET_CONTENT or ACTION_OPEN_DOCUMENT the downloaded file is not visible. In addition, if I rename the file or copy and paste it through the phone's file manager, everything will be fixed in the same path
Also, saving in the downloads folder is done without any problem But when the subfolder is created and it is supposed to be saved there, this problem occurs
There is no problem with downloading by DownloadManager, but i want use retofit
Download function:
suspend fun download(url: String, targetPath: String, progressRetrofit: RetrofitProgress) = flow {
try {
val response = apiService.download(url).awaitResponse()
val body = response.body()
if (response.isSuccessful && body != null) {
try {
val file = File(targetPath)
body.byteStream().use { inputStream ->
FileOutputStream(file).use { outputStream ->
val data = ByteArray(1024)
var read: Int
var currentDownloadSize = 0L
val fileSize = body.contentLength()
while (inputStream.read(data).also { read = it } != -1) {
outputStream.write(data, 0, read)
currentDownloadSize += read
withContext(Dispatchers.Main)
{
progressRetrofit.onProgressUpdate((currentDownloadSize * 100 / fileSize).toInt(), fileSize, currentDownloadSize)
}
}
withContext(Dispatchers.Main)
{
progressRetrofit.onProgressUpdate((currentDownloadSize * 100 / fileSize).toInt(), fileSize, currentDownloadSize)
}
outputStream.close()
outputStream.flush()
}
}
emit(NetworkResult.Success(true))
} catch (e: Exception) {
emit(NetworkResult.Failure(e.message.toString()))
errorMessage(e.message.toString(), true)
}
} else {
emit(NetworkResult.Failure(response.message()))
errorMessage(response.errorBody().toString(), true)
}
} catch (e: Exception) {
emit(NetworkResult.Failure(e.message.toString()))
errorMessage(e.message.toString(), true)
}
}
Hmmmm...
You are right...
It happens.
But only if with ACTION_OPEN_DOCUMENT the user directly uses the Downloads
item.
Instead the user should browse the device, and go to Download
directory and then to the subdirectory.
(Note: The first ends with an s, the real directory is without s.).
After some more tests it appeared if the file was scanned by the MediaStore.
So add some few lines of code to let it be scanned after download.