在安卓应用程序中下载文件(使用kotlin)



我一直在研究如何使用DownloadManagerBroadcastReceiver从互联网下载文件(音频、图像…(。虽然我已经取得了一些进展,取得了一些成果,但它仍然没有完全发挥作用,我找不到一个好的教程来指导我需要做什么。

我在BroadcastReceiveronReceive((方法中得到一个信号,告诉我下载完成了。但我不知道如何利用这个结果,我的意思是访问实际的文件,例如播放音频或显示图像(或对文件做任何事情(。

以下是问题的相关代码:

var brdCstRcvr = object:BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
val id = p1?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (id == downloadID) {
Toast.makeText(applicationContext,"Download Completed !!!",
Toast.LENGTH_LONG).show()
val mgr = applicationContext.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
val uri:Uri = mgr.getUriForDownloadedFile(downloadID)
println("URI="+uri.toString())
println("URI-Path="+uri.path)
// What to do here to make use of the downloaded file?
}
}
}

当运行应用程序时,上面的代码执行:我可以看到消息"下载完成">。我还可以在控制台中看到2println行的结果。我需要的是知道如何使用我所拥有的来访问实际文件。我试过一些我在网上发现的东西,但都没有用。

如果我读对了,那么你就成功下载了文件,并获得了URI。根据该文件的位置(比如它在外部存储器上(,您可能需要处理文件访问权限API。但简而言之,你所需要的只是:

var file = File(uri.getPath())

通过打开uri的输入流,然后从流中读取内容,可以使用文件的uri访问该文件。

InputStream is = getContentResolver().openInputStream(uri):

并且uri.getPath((不提供文件系统路径

如果您在Kotlin中执行这些步骤,您可以从任何WebView 下载文件

1-将这些添加到您的舱单中

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

2-将这些设置添加到您的网络视图

val webViewSettings = binding.your@id@webview(InsideXML).settings 
webViewSettings.javaScriptEnabled = true //Needed 
webViewSettings.domStorageEnabled = true //Needed 
webViewSettings.allowFileAccess = true //Needed 
webViewSettings.loadsImagesAutomatically = true //Needed 
----Yo can have more here but this are needed ----- 

3-处理下载

//handle downloading 
binding.wvBase.setDownloadListener { url, userAgent, contentDisposition, mimeType, _ -> 
val request = DownloadManager.Request( 
Uri.parse(url) 
) 
request.setMimeType(mimeType) 
val cookies: String = CookieManager.getInstance().getCookie(url) 
request.addRequestHeader("cookie", cookies) 
request.addRequestHeader("User-Agent", userAgent) 
// request.setDescription("Downloading File...") 
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType)) 
// request.allowScanningByMediaScanner() 
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) 
request.setDestinationInExternalPublicDir( 
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName( 
url, contentDisposition, mimeType 
) 
) 
val dm = getSystemService(DOWNLOAD_SERVICE) as DownloadManager 
dm.enqueue(request) 
alertdialog() 
} 

在我的例子中,我有一个自定义的警报对话框来控制用户是否说"不"、"是"。

最新更新