WebView实现文件下载功能

时间:2021-10-17 08:36:07

WebView控制调用相应的WEB页面进行展示。安卓源码当碰到页面有下载链接的时候,点击上去是一点反应都没有的。原来是因为WebView默认没有开启文件下载的功能,如果要实现文件下载的功能,需要设置WebView的DownloadListener,通过实现自己的DownloadListener来实现文件的下载。具体操作如下:

1、设置WebView的DownloadListener: 
    webView.setDownloadListener(new MyWebViewDownLoadListener());

2、实现MyWebViewDownLoadListener这个类,具体可以如下这样:

  1. private class MyWebViewDownLoadListener implements DownloadListener{
  2. @Override
  3. public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
  4. long contentLength) {
  5. Log.i("tag", "url="+url);
  6. Log.i("tag", "userAgent="+userAgent);
  7. Log.i("tag", "contentDisposition="+contentDisposition);
  8. Log.i("tag", "mimetype="+mimetype);
  9. Log.i("tag", "contentLength="+contentLength);
  10. Uri uri = Uri.parse(url);
  11. Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  12. startActivity(intent);
  13. }
  14. }

这只是调用系统中已经内置的浏览器进行下载,还没有WebView本身进行的文件下载,不过,这也基本上满足我们的应用场景了。

我在项目中的运用 
android源码项目要求这样: 
1,需要使用WebView加载一个网页; 
2,网页中有文件下载的链接,点击后需要下载文件到SDcard; 
3,然后自动打开文件; 
下面是具体解决办法 
第一步,对WebView进行一系列设置。

  1. WebView webview=(WebView)layout.findViewById(R.id.webview);
  2. webview.getSettings().setJavaScriptEnabled(true);
  3. webview.setWebChromeClient(new MyWebChromeClient());
  4. webview.requestFocus();
  5. //              webview.loadUrl("file:///android_asset/risktest.html");
  6. webview.loadUrl(jcrs_sub.get(position).addr);
  7. // 设置web视图客户端
  8. webview.setWebViewClient(new MyWebViewClient());
  9. webview.setDownloadListener(new MyWebViewDownLoadListener());
  10. //内部类
  11. public class MyWebViewClient extends WebViewClient {
  12. // 如果页面中链接,如果希望点击链接继续在当前browser中响应,
  13. // 而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。
  14. public boolean shouldOverviewUrlLoading(WebView view, String url) {
  15. L.i("shouldOverviewUrlLoading");
  16. view.loadUrl(url);
  17. return true;
  18. }
  19. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  20. L.i("onPageStarted");
  21. showProgress();
  22. }
  23. public void onPageFinished(WebView view, String url) {
  24. L.i("onPageFinished");
  25. closeProgress();
  26. }
  27. public void onReceivedError(WebView view, int errorCode,
  28. String description, String failingUrl) {
  29. L.i("onReceivedError");
  30. closeProgress();
  31. }
  32. }
  33. // 如果不做任何处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身,
  34. // 如果希望浏览的网 页回退而不是推出浏览器,需要在当前Activity中处理并消费掉该Back事件。
  35. public boolean onKeyDown(int keyCode, KeyEvent event) {
  36. // if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){
  37. // webview.goBack();
  38. // return true;
  39. // }
  40. return false;
  41. }

第二步,起线程开始下载文件。

  1. //内部类
  2. private class MyWebViewDownLoadListener implements DownloadListener {
  3. @Override
  4. public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
  5. long contentLength) {
  6. if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  7. Toast t=Toast.makeText(mContext, "需要SD卡。", Toast.LENGTH_LONG);
  8. t.setGravity(Gravity.CENTER, 0, 0);
  9. t.show();
  10. return;
  11. }
  12. DownloaderTask task=new DownloaderTask();
  13. task.execute(url);
  14. }
  15. }
  16. //内部类
  17. private class DownloaderTask extends AsyncTask<String, Void, String> {
  18. public DownloaderTask() {
  19. }
  20. @Override
  21. protected String doInBackground(String... params) {
  22. // TODO Auto-generated method stub
  23. String url=params[0];
  24. //          Log.i("tag", "url="+url);
  25. String fileName=url.substring(url.lastIndexOf("/")+1);
  26. fileName=URLDecoder.decode(fileName);
  27. Log.i("tag", "fileName="+fileName);
  28. File directory=Environment.getExternalStorageDirectory();
  29. File file=new File(directory,fileName);
  30. if(file.exists()){
  31. Log.i("tag", "The file has already exists.");
  32. return fileName;
  33. }
  34. try {
  35. HttpClient client = new DefaultHttpClient();
  36. //                client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
  37. HttpGet get = new HttpGet(url);
  38. HttpResponse response = client.execute(get);
  39. if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
  40. HttpEntity entity = response.getEntity();
  41. InputStream input = entity.getContent();
  42. writeToSDCard(fileName,input);
  43. input.close();
  44. //                  entity.consumeContent();
  45. return fileName;
  46. }else{
  47. return null;
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. return null;
  52. }
  53. }
  54. @Override
  55. protected void onCancelled() {
  56. // TODO Auto-generated method stub
  57. super.onCancelled();
  58. }
  59. @Override
  60. protected void onPostExecute(String result) {
  61. // TODO Auto-generated method stub
  62. super.onPostExecute(result);
  63. closeProgressDialog();
  64. if(result==null){
  65. Toast t=Toast.makeText(mContext, "连接错误!请稍后再试!", Toast.LENGTH_LONG);
  66. t.setGravity(Gravity.CENTER, 0, 0);
  67. t.show();
  68. return;
  69. }
  70. Toast t=Toast.makeText(mContext, "已保存到SD卡。", Toast.LENGTH_LONG);
  71. t.setGravity(Gravity.CENTER, 0, 0);
  72. t.show();
  73. File directory=Environment.getExternalStorageDirectory();
  74. File file=new File(directory,result);
  75. Log.i("tag", "Path="+file.getAbsolutePath());
  76. Intent intent = getFileIntent(file);
  77. startActivity(intent);
  78. }
  79. @Override
  80. protected void onPreExecute() {
  81. // TODO Auto-generated method stub
  82. super.onPreExecute();
  83. showProgressDialog();
  84. }
  85. @Override
  86. protected void onProgressUpdate(Void... values) {
  87. // TODO Auto-generated method stub
  88. super.onProgressUpdate(values);
  89. }
  90. }

第三步,实现一些工具方法。

  1. <span style="font-family:Helvetica, Tahoma, Arial, sans-serif;">private ProgressDialog mDialog;
  2. private void showProgressDialog(){
  3. if(mDialog==null){
  4. mDialog = new ProgressDialog(mContext);
  5. mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
  6. mDialog.setMessage("正在加载 ,请等待...");
  7. mDialog.setIndeterminate(false);//设置进度条是否为不明确
  8. mDialog.setCancelable(true);//设置进度条是否可以按退回键取消
  9. mDialog.setCanceledOnTouchOutside(false);
  10. mDialog.setOnDismissListener(new OnDismissListener() {
  11. @Override
  12. public void onDismiss(DialogInterface dialog) {
  13. // TODO Auto-generated method stub
  14. mDialog=null;
  15. }
  16. });
  17. mDialog.show();
  18. }
  19. }
  20. private void closeProgressDialog(){
  21. if(mDialog!=null){
  22. mDialog.dismiss();
  23. mDialog=null;
  24. }
  25. }
  26. public Intent getFileIntent(File file){
  27. //       Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
  28. Uri uri = Uri.fromFile(file);
  29. String type = getMIMEType(file);
  30. Log.i("tag", "type="+type);
  31. Intent intent = new Intent("android.intent.action.VIEW");
  32. intent.addCategory("android.intent.category.DEFAULT");
  33. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  34. intent.setDataAndType(uri, type);
  35. return intent;
  36. }
  37. public void writeToSDCard(String fileName,InputStream input){
  38. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  39. File directory=Environment.getExternalStorageDirectory();
  40. File file=new File(directory,fileName);
  41. //          if(file.exists()){
  42. //              Log.i("tag", "The file has already exists.");
  43. //              return;
  44. //          }
  45. try {
  46. FileOutputStream fos = new FileOutputStream(file);
  47. byte[] b = new byte[2048];
  48. int j = 0;
  49. while ((j = input.read(b)) != -1) {
  50. fos.write(b, 0, j);
  51. }
  52. fos.flush();
  53. fos.close();
  54. } catch (FileNotFoundException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. } catch (IOException e) {
  58. // TODO Auto-generated catch block
  59. e.printStackTrace();
  60. }
  61. }else{
  62. Log.i("tag", "NO SDCard.");
  63. }
  64. }
  65. private String getMIMEType(File f){
  66. String type="";
  67. String fName=f.getName();
  68. /* 取得扩展名 */
  69. String end=fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
  70. /* 依扩展名的类型决定MimeType */
  71. if(end.equals("pdf")){
  72. type = "application/pdf";//
  73. }
  74. else if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
  75. end.equals("xmf")||end.equals("ogg")||end.equals("wav")){
  76. type = "audio/*";
  77. }
  78. else if(end.equals("3gp")||end.equals("mp4")){
  79. type = "video/*";
  80. }
  81. else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
  82. end.equals("jpeg")||end.equals("bmp")){
  83. type = "image/*";
  84. }
  85. else if(end.equals("apk")){
  86. /* android.permission.INSTALL_PACKAGES */
  87. type = "application/vnd.android.package-archive";
  88. }
  89. //      else if(end.equals("pptx")||end.equals("ppt")){
  90. //        type = "application/vnd.ms-powerpoint";
  91. //      }else if(end.equals("docx")||end.equals("doc")){
  92. //        type = "application/vnd.ms-word";
  93. //      }else if(end.equals("xlsx")||end.equals("xls")){
  94. //        type = "application/vnd.ms-excel";
  95. //      }
  96. else{
  97. //        /*如果无法直接打开,就跳出软件列表给用户选择 */
  98. type="*/*";
  99. }
  100. return type;
  101. }   </span>
  1. <span style="font-family:Helvetica, Tahoma, Arial, sans-serif;">转自:<a href="http://gundumw100.iteye.com/blog/1338645">http://gundumw100.iteye.com/blog/1338645</a>
  2. </span>

WebView实现文件下载功能源码搜藏网整理,转载请注明出处http://www.codesocang.com/jiaocheng/shoujikaifa/9993.html