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

對當前的WebView設置下載監聽dom

 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);
  }
});

 

下載文件核心代碼:ide

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(); }

 

須要注意的點:this

1.須要單啓動一個線程,不能在主線程執行文件下載的操做.url

2.下載的文件名,長度有限制,推薦文件的名稱的長度控制在100.防止出現IOException: open failed: ENAMETOOLONG (File name too long)錯誤,致使下載的任務沒法正常開始.  緣由: Java語言規範中對文件名的長度是沒有限制的。可是操做系統對文件名的長度有限制,最多見的是255個字節,這個限制長度包括文件名的後綴,如.mp3,.mkv等。spa

相關文章
相關標籤/搜索