WebView下载文件并显示进度

1.activity

package com.sam.more.activitys.webview;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

import com.sam.more.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebViewDownloadActivity extends AppCompatActivity implements DownloadCallback {

    @BindView(R.id.webv_download)
    WebView webvDownload;
    @BindView(R.id.et_url)
    EditText etUrl;
    @BindView(R.id.btn_download)
    Button btnDownload;

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_download);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        webvDownload.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webvDownload.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                new Thread(new DownLoadThread(url, WebViewDownloadActivity.this)).start();
            }
        });
    }

    @OnClick({R.id.btn_download})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_download:
                webvDownload.loadUrl(etUrl.getText().toString().trim());
                break;
        }
    }

    @Override
    public void percentage(final String percentage) {
        Message message = new Message();
        message.obj = percentage;
        mHandler.sendMessage(message);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.obj.toString().equals("100%")) {
                btnDownload.setText("下载完成");
                mHandler.removeCallbacksAndMessages(null);
                return false;
            }
            btnDownload.setText(message.obj.toString());
            return true;
        }
    });
}

2.layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activitys.webview.WebViewDownloadActivity">

    <EditText
        android:id="@+id/et_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://csdn-app.csdn.net/csdn.apk" />

    <Button
        android:id="@+id/btn_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载" />

    <WebView
        android:id="@+id/webv_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

3.thread

package com.sam.more.activitys.webview;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

/**
 * Author: Sam
 * Date: 2021-03-13 11:32
 * Description:
 */

public class DownLoadThread implements Runnable {

    private String dlUrl;
    private DownloadCallback callback;

    DownLoadThread(String dlUrl, DownloadCallback callback) {
        this.dlUrl = dlUrl;
        this.callback = callback;
    }

    @Override
    public void run() {
        InputStream in = null;
        FileOutputStream fout = null;
        int contentLength, downedFileLength = 0;//文件总大小,已下载大小
        DecimalFormat df = new DecimalFormat("0%");
        try {
            URL httpUrl = new URL(dlUrl);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            contentLength = conn.getContentLength();
            Log.e("文件总大小", contentLength + "");
            in = conn.getInputStream();
            File downloadFile, sdFile;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Log.e("sam", "SD卡可写");
                downloadFile = Environment.getExternalStorageDirectory();
                sdFile = new File(downloadFile, "csdn_client.apk");
                fout = new FileOutputStream(sdFile);
            } else {
                Log.e("sam", "SD卡不存在或者不可读写");
            }
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                if (fout != null) {
                    fout.write(buffer, 0, len);
                    downedFileLength += len;
                    callback.percentage(df.format((float) downedFileLength / contentLength));
                }
            }
        } 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();
                }
            }
        }
    }
}

4.callback

package com.sam.more.activitys.webview;

/**
 * Author: Sam
 * Date: 2021-03-13 13:22
 * Description:
 */

public interface DownloadCallback {

    void percentage(String percentage);
}

到这就已经OK啦,如果对您有一点点帮助,还请给个赞,谢谢!

上一篇:Android之webview性能优化


下一篇:关于安卓中的 shouldOverrideUrlLoading 方法的问题