🌱 dreaming DiNO
[Kotlin] url > DownloadManager로 파일 다운로드 받기 본문
// 파일 다운로드
private var mDownloadManager: DownloadManager? = null
private var mDownloadQueueId: Long? = null
private val downloadCompleteReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (mDownloadQueueId == reference) {
val query = Query() // 다운로드 항목 조회에 필요한 정보 포함
query.setFilterById(reference)
val cursor = mDownloadManager!!.query(query)
cursor.moveToFirst()
val columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
val columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON)
val status = cursor.getInt(columnIndex)
val reason = cursor.getInt(columnReason)
cursor.close()
when (status) {
DownloadManager.STATUS_SUCCESSFUL -> Toast.makeText(this@MainActivity, "다운로드를 완료하였습니다.", Toast.LENGTH_SHORT).show()
DownloadManager.STATUS_PAUSED -> Toast.makeText(this@MainActivity, "다운로드가 중단되었습니다.", Toast.LENGTH_SHORT).show()
DownloadManager.STATUS_FAILED -> Toast.makeText(this@MainActivity, "다운로드가 취소되었습니다.", Toast.LENGTH_SHORT).show()
}
}
}
}
private fun downloadFile(fileUrl: String) {
TDebugLog.i(logTag, "downloadFile-()")
TDebugLog.d(logTag, "fileUrl: $fileUrl")
val mimetype = getMimeType(fileUrl)
val fileName = Uri.parse(fileUrl).getQueryParameter("file_nm")
val outputFilePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS + "/$fileName")
if (mDownloadManager == null) {
mDownloadManager = this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
}
val outputFile = File(outputFilePath.toString())
if (!outputFile.parentFile?.exists()!!) {
outputFile.parentFile?.mkdirs()
}
val downloadUri: Uri = Uri.parse(fileUrl)
val request = DownloadManager.Request(downloadUri)
val pathSegmentList = downloadUri.pathSegments
request.setTitle("$fileName")
request.setMimeType(mimetype)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationUri(Uri.fromFile(outputFile))
request.setAllowedOverMetered(true)
mDownloadQueueId = mDownloadManager!!.enqueue(request)
}
private fun getMimeType(url:String): String {
var mimetype = ""
val extension = url.split(".")
if (extension.isEmpty())
return mimetype
mimetype = when (extension[extension.size-1]) {
"pdf"-> "application/pdf"
"doc"-> "application/msword"
"xls"-> "application/vnd.ms-excel"
"js" -> "application/x-javascript"
"zip"-> "application/zip"
"png"-> "image/png"
"jpeg", "jpg", "jpe"-> "image/jpeg"
"css" -> "text/css"
"html", "htm"-> "text/html"
"txt"-> "text/plain"
"xml"-> "text/xml"
"xsl"-> "text/xsl"
else-> ""
}
return mimetype
}
override fun onResume() {
TDebugLog.i(logTag, "onResume-()")
super.onResume()
val completeFilter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
registerReceiver(downloadCompleteReceiver, completeFilter)
}
override fun onPause() {
TDebugLog.i(logTag, "onPause-()")
super.onPause()
unregisterReceiver(downloadCompleteReceiver)
}