Android WebView下载apk

这里写图片描述
  
  出于想要更深入地了解WebView的使用想法下,尝试了下在WebView中下载资源,原来通过WebView可以监听它的下载事件,来查看WebView中的下载,但是单单监听它的下载事件,实际上我们并不知道文件下载完成与否,这里我们可以调用系统的通知来知道是否下载完成,就像上面图片演示的,下载的时候会出现一个系统通知了。
  因为下载操作是一个耗时操作,因此我们需要新开一个线程进行下载。

思路:

1、在MainActivity中对WebView的DownLoad事件进行监听。
2、写一个implements DownloadListener的class,在这个类中重写onDownloadStart方法,在该方法中开启一个新的线程 
3、写一个extends Thread的class,通过URL连接实现读入与写出。

1、WebView监听Download
 mwebview.setDownloadListener(new MyDownload());
2、调用系统通知与开启线程
 class  MyDownload implements DownloadListener{

        @Override
        public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype, long contentLength) {
            //检测是下载apk
            if(url.endsWith(".apk")){
            //通过uri与Intent来调用系统通知,查看进度
                Uri uri=Uri.parse(url);
                Intent intent=new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
                new DownloadThread(url).start();
            }           
        }       
    }
3、新建线程,进行读入与写出
public class DownloadThread extends Thread{
    private String urlpath;

    public DownloadThread(String url) {

        this.urlpath = url;
    }
  @Override
public void run() {
    try {
        URL url=new URL(urlpath);
        URLConnection conn=url.openConnection();
        InputStream is=conn.getInputStream();
        //检测sdcard是否挂载
        if(Environment.getExternalStorageState()==(Environment.MEDIA_MOUNTED)){     
        File file=new File(Environment.getExternalStorageDirectory(),"yingyong.apk");
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream os = new FileOutputStream(file);
        byte[] array=new byte[1024];
        int index=is.read(array);
        while(index!=-1){
            os.write(array, 0, index);
            index=is.read(array);
        }
        if(os!=null){
            os.flush();
            os.close();
        }
        if(is!=null){
            is.close();
        }
    }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}
最后不要忘记在manifest中添加对sdcard的读写权限。
  <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值