使用函数
WebView默认没有开启文件下载的功能,如果想使得WebView能够支持文件下载,就需要给WebView设置下载监听器setDownloadListener,每当有文件需要下载时,就会回调onDownloadStart。
Java版一
mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
// 处理下载事件
downloadByBrowser(url);
}
});
Java版二
mWebView.setDownloadListener(new MyDownloadListener());
Kotlin版一
mWebView.setDownloadListener(object : DownloadListener{
override fun onDownloadStart(
url: String?,
userAgent: String?,
contentDisposition: String?,
mimeType: String?,
contentLength: Long
) {
// 处理下载事件
if (!url.isNullOrEmpty()){
downloadByBrowser(url)
}
}
})
Kotlin版二
mWebView.setDownloadListener(MyDownloadListener(this@MainActivity))
具体函数编写
Java版一
/** 调起浏览器下载 */
private void downloadByBrowser(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(url));
startActivity(intent);
}
Java版二
/** 调起浏览器下载 */
private class MyDownloadListener implements DownloadListener {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(uri );
startActivity(intent);
}
}
Kotlin版一
/** 调起浏览器下载 */
private fun downloadByBrowser(url: String) {
val intent = Intent(Intent.ACTION_VIEW)
intent.addCategory(Intent.CATEGORY_BROWSABLE)
intent.setData(Uri.parse(url))
startActivity(intent)
}
Kotlin版二
/** 调起浏览器下载 */
private class MyDownloadListener(val context: Context) : DownloadListener {
override fun onDownloadStart(url: String?, userAgent: String?, contentDisposition: String?, mimeType: String?, contentLength: Long) {
val intent = Intent(Intent.ACTION_VIEW)
intent.addCategory(Intent.CATEGORY_BROWSABLE)
intent.setData(Uri.parse(url))
context.startActivity(intent)
}
}
Kotlin版二context复杂版
private class MyDownloadListener : DownloadListener{
private var mContext :Context?= null
constructor(context: Context):super(){
mContext = context
}
override fun onDownloadStart(url: String?, userAgent: String?, contentDisposition: String?, mimeType: String?, contentLength: Long) {
val intent = Intent(Intent.ACTION_VIEW)
intent.addCategory(Intent.CATEGORY_BROWSABLE)
intent.setData(Uri.parse(url))
mContext?.startActivity(intent)
}
}