前言
最近发现项目中的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>
这样基本就差不多可以了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。