你好,游客 登录 注册 搜索
背景:
阅读新闻

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

[日期:2017-05-25] 来源:Linux社区  作者:renhui [字体:大 中 小]

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等。

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-05/144236.htm

linux
相关资讯       Android webview 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款