Android 浏览器 —— 使用 WebView 实现文件下载
生活随笔
收集整理的這篇文章主要介紹了
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 实现文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 20169210《Linux内核原理与分
- 下一篇: 【java】定时器