首页 > 系统 > Android > 正文

Android在WebView中调用系统下载的方法

2019-10-22 18:10:41
字体:
来源:转载
供稿:网友

前言

最近发现项目中的WebView加载下载页的时候是一片空白,没有出现下载,于是简单的调用了系统的下载对其进行下载。

过程

自定义一个下载监听,实现了DownloadListener这个接口

class MyDownloadStart implements DownloadListener{  @Override  public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {   downUrl = url;   //从链接里获取文件名   String dirNameString = url.substring(url.lastIndexOf("/") + 1);   //获得下载文件的大小   DecimalFormat decimalFormat = new DecimalFormat("0.00");   float size = contentLength;   dirName.setText(dirNameString);   if (size < 1024){    dirSize.setText(size + "B");   }else if (size < 1048576){    String dirSizeStringKB = decimalFormat.format(size / 1024);    dirSize.setText(dirSizeStringKB + "K");   }else if (size < 1073741824){    String dirSizeString = decimalFormat.format(size / 1048576);    dirSize.setText(dirSizeString + "M");   }else {    String dirStringG = decimalFormat.format(size / 1073741824);    dirSize.setText(dirStringG + "G");   }   //显示是否下载的dialog   downdialog.show();  }}

将MyDownloadStart设置到WebView上;

mWebView.setWebViewDownListener(new MyDownloadStart());

设置Dialog,点击是调用系统下载

DownloadManager downloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));//下载时,下载完成后显示通知request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//下载的路径,第一个参数是文件夹名称,第二个参数是下载的文件名request.setDestinationInExternalPublicDir("SooDown",dirName.getText().toString());request.setVisibleInDownloadsUi(true);downloadManager.enqueue(request);

这样就可以进行下载了,但是我们是不知道什么时候下载完成的。通过DownloadManager下载完成系统会发送条广播,我们要做的是要接收到该广播并进行处理

public class DownloadReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) {  DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);  if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){   Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT).show();  }else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){   //点击通知栏进入下载管理页面   Intent intent1 = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);   intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   context.startActivity(intent1);  } }}

最后一步,不要忘记配置BroadcastReceiver

在AndroidManifest.xml中配置

<receiver android:name=".Utils.DownloadReceiver">   <intent-filter>    <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>    <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/>   </intent-filter></receiver>

这样基本就差不多可以了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表