日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android 浏览器 —— 使用 WebView 实现文件下载

發布時間:2025/6/17 Android 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 浏览器 —— 使用 WebView 实现文件下载 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對當前的WebView設置下載監聽

mCurrentWebView.setDownloadListener(new DownloadListener() {@Overridepublic void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {// TODO 實現下載邏輯Log.e("onDownloadStart", "url===" + url + "---userAgent=" + userAgent + "---contentDisposition=" + contentDisposition + "---mimetype=" + mimetype + "---contentLength=" + contentLength);} });

?

下載文件核心代碼:

HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpGet httpGet = new HttpGet(url);try {File file = new File(Environment.getExternalStorageDirectory(), fileName);if (!file.exists()) {file.createNewFile();} else {boolean flag = file.delete();if (flag) {file.createNewFile();} else {return;}
  }RandomAccessFile randomFile
= new RandomAccessFile(file, "rw");HttpResponse response = new DefaultHttpClient(params).execute(httpGet);HttpEntity entity = response.getEntity();InputStream in = entity.getContent();randomFile.seek(randomFile.length());byte[] buffer = new byte[1024];int lenght = 0;while ((lenght = in.read(buffer)) > 0) {randomFile.write(buffer, 0, lenght);DebugTraceTool.debugTraceE(this, "file length == " + randomFile.length());}randomFile.close();httpGet.abort();} catch (Exception e) {e.printStackTrace(); }

?

需要注意的點:

1.需要單啟動一個線程,不能在主線程執行文件下載的操作.

2.下載的文件名,長度有限制,推薦文件的名稱的長度控制在100.防止出現IOException: open failed: ENAMETOOLONG (File name too long)錯誤,導致下載的任務無法正常開始. ?原因: Java語言規范中對文件名的長度是沒有限制的。但是操作系統對文件名的長度有限制,最常見的是255個字節,這個限制長度包括文件名的后綴,如.mp3,.mkv等。

?

轉載于:https://www.cnblogs.com/renhui/p/6144639.html

總結

以上是生活随笔為你收集整理的Android 浏览器 —— 使用 WebView 实现文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。