美文网首页
android webview开发:下载

android webview开发:下载

作者: 欢乐的饲养员 | 来源:发表于2018-12-24 14:10 被阅读0次

    使用场景

    webview加载网址的时候 如果碰到非网页类型,未做处理的话,webview会报错(出现浏览器崩溃的界面)。
    这是因为webview无法加载非网页类型界面,导致界面崩溃,但是浏览器内部有相关api。

      webview.setDownloadListener(DownloadListener listener)
    

    只要设置这个监听事件,就可以在要发生下载请求的时候,进行下载。

    使用接口

    在DownloadListener这个接口里可以可以实现下载的方法。
    重写下载的onDownloadStart()方法就行了

       void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength);
      //url         String:应下载的内容的完整URL
      //userAgent   String:用于下载的用户代理。
      //contentDisposition  String:Content-disposition http标头,如果存在。
      //mimetype    String:服务器报告的内容的mimetype
      //contentLength   long:服务器报告的文件大小
    

    实现方法

    ps:不管用啥方法,都要注意androidM的动态权限问题;

    推荐方案(最方便)

    系统自带的DownloadManager
     DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                        // 允许媒体扫描,根据下载的文件类型被加入相册、音乐等媒体库
                        request.allowScanningByMediaScanner();
                        // 设置通知的显示类型,下载进行时和完成后显示通知
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        // 设置通知栏的标题,如果不设置,默认使用文件名
                        request.setTitle("下载完成");
                        // 设置通知栏的描述
    //                    request.setDescription("This is description");
                        // 允许在计费流量下下载
                        request.setAllowedOverMetered(true);
                        // 允许该记录在下载管理界面可见
                        request.setVisibleInDownloadsUi(true);
                        // 允许漫游时下载
                        request.setAllowedOverRoaming(true);
    
                        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
                        Log.e("fileName:{}", fileName);
                        request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory() + "/Download/", fileName);
    
    
                        final DownloadManager downloadManager = (DownloadManager) iWebView.getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                        // 添加一个下载任务
                        long downloadId = downloadManager.enqueue(request);
    

    ps:不需要判断androidN的URI的问题哦

    另外也可以用okhttps进行下载也很方便~(稍微注意下androidN的问题)

    相关文章

      网友评论

          本文标题:android webview开发:下载

          本文链接:https://www.haomeiwen.com/subject/xlzakqtx.html