I need to put GIF to input connection https://developer.android.com/guide/topics/text/image-keyboard.html
But i have a problem because i need to take uri of this GIF. I donwload it like a file and can get only path to it. And how i can get the URI ? Or i need to do this in another way ?
Glide.with(this)
.asFile()
.load(contentURL)
.downloadOnly(object: SimpleTarget<File>(){
override fun onResourceReady(resource: File, transition: Transition<in File>?) {}
UPDATE (tested)
Option 1: Use Glide
private suspend fun downloadImage(context: Context, imageUrl: String, fileName: String, folderName: String) {
withContext(Dispatchers.IO) {
val gifBuffer = Glide.with(context).asGif().load(imageUrl).submit().get().buffer
val imageUri = getImageUri(getApplication(), fileName, folderName)
context.contentResolver.openOutputStream(imageUri).use {
val bytes = ByteArray(gifBuffer.capacity())
(gifBuffer.clear() as ByteBuffer).get(bytes) //Both ".clear()" and "as ByteBuffer" are mandatory!!
it?.write(bytes)
}
}
}
Option 2: Use URL(url).openStream()
private suspend fun downloadImage(context: Context, imageUrl: String, fileName: String, folderName: String) {
withContext(Dispatchers.IO) {
val imageUri = getImageUri(getApplication(), fileName, folderName)
URL(imageUrl).openStream().use { inputStream ->
context.contentResolver.openOutputStream(imageUri).use { outputStream ->
inputStream.copyTo(outputStream!!)
}
}
}
}
I think you should use DownloadManager
to achieve it, which has setDestinationUri()
.
Helpful video: https://youtu.be/SmXGlv7QEO0?t=642
Helpful reading: https://medium.com/@aungkyawmyint_26195/downloading-file-properly-in-android-d8cc28d25aca
Remember to generate the image file uri
first:
private fun getNewImageUri(fileName: String, folderName: String): Uri { //create new file
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) //file name
put(MediaStore.MediaColumns.MIME_TYPE, "image/gif") //file type
put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOAD}/$folderName") //file location
}
return requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
}