Created
March 2, 2022 19:48
-
-
Save raystatic/62c647afae64c1424fb28ce744647a2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun getSavedFileUri( | |
fileName:String, | |
fileType:String, | |
fileUrl:String, | |
context: Context): Uri?{ | |
val mimeType = when(fileType){ | |
"PDF" -> "application/pdf" | |
"PNG" -> "image/png" | |
"MP4" -> "video/mp4" | |
else -> "" | |
} // different types of files will have different mime type | |
if (mimeType.isEmpty()) return null | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ | |
val contentValues = ContentValues().apply { | |
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) | |
put(MediaStore.MediaColumns.MIME_TYPE, mimeType) | |
put(MediaStore.MediaColumns.RELATIVE_PATH, "Download/DownloaderDemo") | |
} | |
val resolver = context.contentResolver | |
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues) | |
return if (uri!=null){ | |
URL(fileUrl).openStream().use { input-> | |
resolver.openOutputStream(uri).use { output-> | |
input.copyTo(output!!, DEFAULT_BUFFER_SIZE) | |
} | |
} | |
uri | |
}else{ | |
null | |
} | |
}else{ | |
val target = File( | |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), | |
fileName | |
) | |
URL(fileUrl).openStream().use { input-> | |
FileOutputStream(target).use { output -> | |
input.copyTo(output) | |
} | |
} | |
return target.toUri() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment