最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android DownloadMananger管理器實(shí)現(xiàn)下載圖片功能

 更新時(shí)間:2023年01月05日 08:32:14   作者:知奕奕  
Android DownloadMananger類似于下載隊(duì)列,管理所有當(dāng)前正在下載或者等待下載的項(xiàng)目,他可以維持HTTP鏈接,并且在隊(duì)列中的下載項(xiàng)目一旦失敗,還能自動(dòng)重新下載

DownloadManager三大組件介紹

DownloadManager

類似于下載隊(duì)列,管理所有當(dāng)前正在下載或者等待下載的項(xiàng)目;

他可以維持 HTTP 鏈接,并且在隊(duì)列中的下載項(xiàng)目一旦失敗,還能自動(dòng)重新下載!

一般采取如下固定格式創(chuàng)建一個(gè) DownloadManager

downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

整個(gè)下載過程需要添加的權(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,即通過下載項(xiàng)目的 id 來 query(查詢) 到對應(yīng)項(xiàng)目信息

fun getDownloadList(id: Long) {
    // 首選使用DownloadManager.Query()創(chuàng)建query對象
    val query = DownloadManager.Query().setFilterById(id)
    // 然后對downloadManager進(jìn)行查詢,得到cursor對象
    val cursor = downloadManager.query(query)
    // 簡單的打印一下cursor對象
    println(cursor)
}

DownloadManager.Request

重頭戲,使用它可以執(zhí)行下載操作

Request 接收的第一個(gè)參數(shù)是一個(gè)下載地址的 Uri 形式,我們可以使用 Uri.parse 把原下載地址變成 uri 形式的!

使用 apply 函數(shù)來執(zhí)行,可以簡化代碼

// 發(fā)起一個(gè)request請求,請求的下載地址為downloadUri
// 使用apply函數(shù)設(shè)置下載的對應(yīng)參數(shù)
var request = DownloadManager.Request(downloadUri).apply {
    // 下載時(shí)在通知欄內(nèi)顯示下載進(jìn)度條
    // 這是固定格式,抄就好了
    setNotificationVisibility(
        DownloadManager.Request.VISIBILITY_VISIBLE
                or DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
    )
    // 設(shè)置MIME類型,即設(shè)置下載文件的類型
    // 如果下載的是android文件,那么類型應(yīng)當(dāng)設(shè)置為application/vnd.android.package-archive
    setMimeType(filter)
    // 設(shè)置通知欄中下載標(biāo)題
    setTitle(title)
    // 設(shè)置通知欄中下載詳細(xì)內(nèi)容介紹
    setDescription(description)
    // 設(shè)置下載文件保存在SDCard中的那一個(gè)公開目錄
    setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadName)
}

下載圖片小案例

工具類 DownloadUtils.kt

在這個(gè)工具類內(nèi),我們將編寫 download 下載方法,便于我們后續(xù)直接復(fù)用;

首先添加一個(gè)下載管理器,并設(shè)置他為延后初始化:

lateinit var downloadManager: DownloadManager

第二步,創(chuàng)建下載方法;

titledescription 分別表示通知欄內(nèi)下載標(biāo)題和詳細(xì)介紹;

downloadName 表示下載好的文件名稱

downloadUri 就是下載地址了

filter 即下載文件時(shí)使用的過濾器

fun download(
    context: Context,
    title: String = "下載文件",
    description: String = "正在下載,請稍后...",
    downloadName: String,
    downloadUri: Uri,
    filter: String
) {}

第三步,創(chuàng)建一個(gè) request 下載,然后把該 request 塞到下載管理器里面進(jìn)行管理:

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)建一個(gè)監(jiān)聽器,用于監(jiān)聽文件下載完畢事件和通知欄點(diǎ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 -> {
            }
        }
    }
    // 別忘了這里還有一個(gè)IntentFilter作為過濾器使用?。?!
}, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))

主類調(diào)用下載方法

最后一步,直接在 mainactivity 中進(jìn)行調(diào)用就好啦!

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    // 點(diǎn)擊按鈕,即可開始下載
    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管理器實(shí)現(xiàn)下載圖片功能的文章就介紹到這了,更多相關(guān)Android DownloadMananger內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

麻栗坡县| 阿坝县| 宾阳县| 梨树县| 洪泽县| 乳源| 密山市| 定襄县| 丹东市| 新兴县| 沙洋县| 鸡东县| 会昌县| 静宁县| 马鞍山市| 枝江市| 荥阳市| 武川县| 万州区| 方山县| 花莲市| 乌什县| 张家港市| 威海市| 镇江市| 兴文县| 潞城市| 古蔺县| 伊川县| 南康市| 河北省| 张家口市| 新乐市| 新乡县| 全州县| 天峻县| 舞阳县| 从化市| 自治县| 九龙城区| 辽中县|