本节给大家介绍的是WebView下载文件的知识点,当我们在使用普通浏览器的时候,比如UC, 当我们点击到一个可供下载链接的时候,就会进行下载,WebView作为一个浏览器般的组件, 当然也是支持下载,我们可以自己来写下载的流程,设置下载后的文件放哪,以什么文件名 保存,当然也可以调用其它内置的浏览器来进行下载
这个很简单,我们只需为WebView设置setDownloadListener,然后重写DownloadListener的 onDownloadStart,然后在里面写个Intent,然后startActivity对应的Activity即可!
方式1:捕获下载Action抛给浏览器执行
wView.setDownloadListener(new DownloadListener(){
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}});
方式2:自己写线程下载文件
public class DownLoadThread implements Runnable {
private String dlUrl;
public DownLoadThread(String dlUrl) {
this.dlUrl = dlUrl;
}
@Override
public void run() {
InputStream in = null;
FileOutputStream fout = null;
try {
URL httpUrl = new URL(dlUrl);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
in = conn.getInputStream();
File downloadFile, sdFile;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
downloadFile = Environment.getExternalStorageDirectory();
sdFile = new File(downloadFile, "csdn_client.apk");
fout = new FileOutputStream(sdFile);
}else{
toast.show("SD卡不存在或者不可读写!");
}
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
fout.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}}
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}}
}
}
}
wView.setDownloadListener(new DownloadListener(){
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,String mimetype, long contentLength) {
new Thread(new DownLoadThread(url)).start();
}});
完成!!!