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

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

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

DownloadManager三大組件介紹

DownloadManager

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

他可以維持 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進(jìn)行查詢,得到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)顯示下載進(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中的那一個公開目錄
    setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadName)
}

下載圖片小案例

工具類 DownloadUtils.kt

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

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

lateinit var downloadManager: DownloadManager

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

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

downloadName 表示下載好的文件名稱

downloadUri 就是下載地址了

filter 即下載文件時使用的過濾器

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

第三步,創(chuàng)建一個 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)建一個監(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 中進(jìn)行調(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)文章

最新評論

涞源县| 永吉县| 石门县| 武威市| 贡嘎县| 灵武市| 通化市| 安岳县| 马鞍山市| 越西县| 吉隆县| 河南省| 沈丘县| 株洲县| 南丰县| 上林县| 太康县| 开化县| 台北市| 普兰县| 上林县| 手机| 米林县| 呼伦贝尔市| 托里县| 珠海市| 个旧市| 兰溪市| 斗六市| 岢岚县| 梅州市| 兴和县| 朝阳市| 西畴县| 杂多县| 舞钢市| 库尔勒市| 化德县| 正镶白旗| 凤山县| 怀安县|