1> 为Handel下载过程创建一个接口
interface Downloader { fun downloadFile(url:String,fileSubPath:String):Long }
创建一个用于处理下载管理的类(在我的情况下,我创建了一个名为AndroidDownloader的类),并按照以下步骤进行操作。
class AndroidDownloader(context: Context):Downloader {
private val downloadManager = context.getSystemService(DownloadManager::class.java)
override fun downloadFile(url: String,fileSubPath:String): Long {
val request = DownloadManager.Request(url.toUri())
.setMimeType("*/*")
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setTitle("Downloading")
.addRequestHeader("Authorization", "Bearer <token>")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileSubPath)
return downloadManager.enqueue(request)
} }
3> 现在创建一个 BroadCastReciver 类来监控文件下载过程。(在我的情况下,我创建了一个 DownloadCompleteReceiver 类)
class DownloadCompleteReceiver:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action == "android.intent.action.DOWNLOAD_COMPLETE") {
val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L)
if(id != -1L) {
println("Download with ID $id finished!")
context?.toast(context.resources.getString(R.string.text_file_download_successfully))
}
}
} }
4> 现在在
AndroidManifest.xml 中注册您的 BroadcastReceiver
<receiver
android:name=".utils.DownloadCompleteReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
5> 最后的步骤,在您想要下载文件的活动或片段中添加以下行。
val downloader=AndroidDownloader(context)
downloader.downloadFile(url,"total${Date().time}.$excitationPath")