Created
April 20, 2020 13:42
-
-
Save jisungbin/8c26081c7630de95a82fc80bd899886c 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
package com.sungbin.autoreply.bot.three.utils | |
import android.content.Context | |
import android.os.AsyncTask | |
import android.widget.ImageView | |
import com.sungbin.autoreply.bot.three.utils.ui.Glide | |
import com.sungbin.sungbintool.StorageUtils | |
import com.sungbin.sungbintool.ToastUtils | |
import java.io.File | |
import java.io.FileOutputStream | |
import java.net.HttpURLConnection | |
import java.net.URL | |
object ImageUtils { | |
fun download(name: String, url: String, context: Context) { | |
val path = getDownloadFilePath(name) | |
val parentFile = File(path) | |
if(!parentFile.exists()) parentFile.mkdirs() | |
ImageDownloadTask(context).execute(path, url) | |
} | |
fun checkDownloadFileExist(name: String): Boolean{ | |
return File(getDownloadFilePath(name)).exists() | |
} | |
fun set(path: String, view: ImageView, context: Context){ | |
val name = path.replaceLast("/", "*").split("*")[1] | |
val isDownloadedd = checkDownloadFileExist(name) | |
if(isDownloadedd){ | |
Glide.set(context, getDownloadFilePath(name), view) | |
} | |
else { | |
download(name, path, context) | |
Glide.set(context, path, view) | |
} | |
} | |
fun getDownloadFilePath(name: String): String{ | |
return StorageUtils.sdcard + | |
"/Android/data/com.sungbin.autoreply.bot.three/chat/content/picture/$name" | |
} | |
private fun String.replaceLast(regex: String, replacement: String): String{ | |
val regexIndexOf = this.lastIndexOf(regex) | |
return if(regexIndexOf == -1) this | |
else { | |
this.substring(0, regexIndexOf) + this.substring(regexIndexOf).replace(regex, replacement) | |
} | |
} | |
private class ImageDownloadTask constructor(context: Context) | |
: AsyncTask<String?, Void?, Void?>() { | |
private val ctx = context | |
override fun doInBackground(vararg params: String?): Void? { | |
try { | |
val imageFile = File(params[0]!!) | |
val imgUrl = URL(params[1]) | |
val conn = imgUrl.openConnection() as HttpURLConnection | |
val len = conn.contentLength | |
val tmpByte = ByteArray(len) | |
val `is` = conn.inputStream | |
val fos = FileOutputStream(imageFile) | |
var read: Int | |
while (true) { | |
read = `is`.read(tmpByte) | |
if (read <= 0) { | |
break | |
} | |
fos.write(tmpByte, 0, read) | |
} | |
`is`.close() | |
fos.close() | |
conn.disconnect() | |
} catch (e: Exception) { | |
ToastUtils.show(ctx, "이미지 다운로드 중에 오류가 발생했습니다.\n\n$e", | |
ToastUtils.LONG, ToastUtils.ERROR) | |
} | |
return null | |
} | |
override fun onPostExecute(result: Void?) { | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment