Android 瀏覽器 —— 使用 WebView 實現文件下載


對當前的WebView設置下載監聽

 mCurrentWebView.setDownloadListener(new DownloadListener() {
    @Override
    public 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等。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM