Android DownloadMananger管理器實現(xiàn)下載圖片功能
DownloadManager三大組件介紹
DownloadManager
類似于下載隊列,管理所有當前正在下載或者等待下載的項目;
他可以維持 HTTP 鏈接,并且在隊列中的下載項目一旦失敗,還能自動重新下載!
一般采取如下固定格式創(chuàng)建一個 DownloadManager
downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
整個下載過程需要添加的權(quán)限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
DownloadManager.Query
目前還沒有研究出什么作用來,他一般和 cursor 連用;
使用 query,獲取目前 DownloadManager 中下載內(nèi)容的所有信息;
setFilterById,即通過下載項目的 id 來 query(查詢) 到對應(yīng)項目信息
fun getDownloadList(id: Long) { // 首選使用DownloadManager.Query()創(chuàng)建query對象 val query = DownloadManager.Query().setFilterById(id) // 然后對downloadManager進行查詢,得到cursor對象 val cursor = downloadManager.query(query) // 簡單的打印一下cursor對象 println(cursor) }
DownloadManager.Request
重頭戲,使用它可以執(zhí)行下載操作
Request 接收的第一個參數(shù)是一個下載地址的 Uri 形式,我們可以使用 Uri.parse
把原下載地址變成 uri 形式的!
使用 apply 函數(shù)來執(zhí)行,可以簡化代碼
// 發(fā)起一個request請求,請求的下載地址為downloadUri // 使用apply函數(shù)設(shè)置下載的對應(yīng)參數(shù) var request = DownloadManager.Request(downloadUri).apply { // 下載時在通知欄內(nèi)顯示下載進度條 // 這是固定格式,抄就好了 setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE or DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) // 設(shè)置MIME類型,即設(shè)置下載文件的類型 // 如果下載的是android文件,那么類型應(yīng)當設(shè)置為application/vnd.android.package-archive setMimeType(filter) // 設(shè)置通知欄中下載標題 setTitle(title) // 設(shè)置通知欄中下載詳細內(nèi)容介紹 setDescription(description) // 設(shè)置下載文件保存在SDCard中的那一個公開目錄 setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadName) }
下載圖片小案例
工具類 DownloadUtils.kt
在這個工具類內(nèi),我們將編寫 download 下載方法,便于我們后續(xù)直接復用;
首先添加一個下載管理器,并設(shè)置他為延后初始化:
lateinit var downloadManager: DownloadManager
第二步,創(chuàng)建下載方法;
title
和 description
分別表示通知欄內(nèi)下載標題和詳細介紹;
downloadName
表示下載好的文件名稱
downloadUri
就是下載地址了
filter
即下載文件時使用的過濾器
fun download( context: Context, title: String = "下載文件", description: String = "正在下載,請稍后...", downloadName: String, downloadUri: Uri, filter: String ) {}
第三步,創(chuàng)建一個 request 下載,然后把該 request 塞到下載管理器里面進行管理:
var request = DownloadManager.Request(downloadUri).apply { setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE or DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) setMimeType(filter) setTitle(title) setDescription(description) setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadName) } downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager downloadManager.enqueue(request)
第四步,直接在本方法內(nèi)創(chuàng)建一個監(jiān)聽器,用于監(jiān)聽文件下載完畢事件和通知欄點擊事件;
context.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { // 定義監(jiān)聽到下載完畢后我們要做的事情 DownloadManager.ACTION_DOWNLOAD_COMPLETE -> { // 取出下載ID的辦法 val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) // 使用意圖打開下載文件管理器,具體代碼解釋請看我的另一篇文章,這里不做過多贅述 val intent = Intent().apply { setAction(Intent.ACTION_OPEN_DOCUMENT) addCategory(Intent.CATEGORY_OPENABLE) setType(filter) } context?.startActivity(intent) Toast.makeText(context, "下載完畢", Toast.LENGTH_SHORT).show() } DownloadManager.ACTION_NOTIFICATION_CLICKED -> { } } } // 別忘了這里還有一個IntentFilter作為過濾器使用?。?! }, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
主類調(diào)用下載方法
最后一步,直接在 mainactivity 中進行調(diào)用就好啦!
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 點擊按鈕,即可開始下載 btn.setOnClickListener { val path = Uri.parse( "https://gimg2.baidu.com/image_searc" + "h/src=http%3A%2F%2Fwww.52zzl.co" + "m%2Fuploads%2Fallimg%2F180202%2F4-1P202" + "1U320-53.jpg&refer=http%3A%2F%2Fwww.52zzl.com&a" + "pp=2002&size=f9999,10000&q=a80&n=0&g=0n&" + "fmt=auto?sec=1668251708&t=d98a9" + "6444b2725d59e3654e4f32eca87" ) DownloadUtils.download( this, "保存您的圖片", "正在下載圖片...", "image.png", path, "image/png" ) } }
完整代碼
MainActivity.kt
package com.zhiyiyi.databasedemo import android.app.DownloadManager import android.content.IntentFilter import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Environment import kotlinx.android.synthetic.main.activity_main.* import java.io.File class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn.setOnClickListener { val path = Uri.parse( "https://gimg2.baidu.com/image_searc" + "h/src=http%3A%2F%2Fwww.52zzl.co" + "m%2Fuploads%2Fallimg%2F180202%2F4-1P202" + "1U320-53.jpg&refer=http%3A%2F%2Fwww.52zzl.com&a" + "pp=2002&size=f9999,10000&q=a80&n=0&g=0n&" + "fmt=auto?sec=1668251708&t=d98a9" + "6444b2725d59e3654e4f32eca87" ) DownloadUtils.download( this, "保存您的圖片", "正在下載圖片...", "image.png", path, "image/png" ) } } }
工具類 DownloadUtils.kt 代碼清單
package com.zhiyiyi.databasedemo import android.app.DownloadManager import android.content.BroadcastReceiver import android.content.ClipDescription import android.content.Context import android.content.Intent import android.content.IntentFilter import android.database.Cursor import android.net.Uri import android.os.Environment import android.widget.Toast import androidx.core.content.getSystemService import java.io.File object DownloadUtils { lateinit var downloadManager: DownloadManager fun download( context: Context, title: String = "下載文件", description: String = "正在下載,請稍后...", downloadName: String, downloadUri: Uri, filter: String ) { println("download") var request = DownloadManager.Request(downloadUri).apply { setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE or DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) setMimeType(filter) setTitle(title) setDescription(description) setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadName) } downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager downloadManager.enqueue(request) context.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { DownloadManager.ACTION_DOWNLOAD_COMPLETE -> { val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) val intent = Intent().apply { setAction(Intent.ACTION_OPEN_DOCUMENT) addCategory(Intent.CATEGORY_OPENABLE) setType(filter) } getDownloadList(id) context?.startActivity(intent) Toast.makeText(context, "下載完畢", Toast.LENGTH_SHORT).show() } DownloadManager.ACTION_NOTIFICATION_CLICKED -> { } } } }, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) } }
到此這篇關(guān)于Android DownloadMananger管理器實現(xiàn)下載圖片功能的文章就介紹到這了,更多相關(guān)Android DownloadMananger內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android實現(xiàn)信號強度監(jiān)聽的方法
這篇文章主要介紹了Android實現(xiàn)信號強度監(jiān)聽的方法,是Android手機中很常見的一個實用功能,需要的朋友可以參考下2014-08-08Android中Fragment多層嵌套時onActivityResult無法正確回調(diào)問題的解決方法
這篇文章主要介紹了Android中Fragment多層嵌套時onActivityResult無法正確回調(diào)問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09android imageview圖片居中技巧應(yīng)用
做UI布局,尤其是遇到比較復雜的多重LinearLayout嵌套,常常會被一些比較小的問題困擾上半天,可是無論怎樣設(shè)置layout_gravity屬性,都無法達到效果2012-11-11