安卓OKHTTP 下载文件

时间:2025-02-08 15:22:48
compile '.okhttp3:okhttp:3.3.1'

工具类
public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * @param url          下载连接
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称
     * @param listener     下载监听
     */
    public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
        Request request = new ().url(url).build();
        (request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                (e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                File dir = new File(destFileDir);
                if (!()) {
                    ();
                }
                File file = new File(dir, destFileName);
                try {
                    is = ().byteStream();
                    long total = ().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = (buf)) != -1) {
                        (buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中更新进度条
                        (progress);
                    }
                    ();
                    // 下载完成
                    (file);
                } catch (Exception e) {
                    (e);
                } finally {
                    try {
                        if (is != null)
                            ();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            ();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public interface OnDownloadListener {
        /**
         * @param file 下载成功后的文件
         */
        void onDownloadSuccess(File file);

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * @param e 下载异常信息
         */
        void onDownloadFailed(Exception e);
    }
}

使用方法
().download(url, ().getAbsolutePath(), "", new () {
    @Override
    public void onDownloadSuccess(File file) {
        //下载完成进行相关逻辑操作
        openFile(file);
    }
    @Override
    public void onDownloading(int progress) {
        (progress);
        ("下载百分之"+progress+"%。。。。");
    }

    @Override
    public void onDownloadFailed(Exception e) {
        //下载异常进行相关提示操作
    }
});

    private void openFile(final File file) {
        // TODO Auto-generated method stub
        if (file != null) {
            Intent intent = new Intent();
            (Intent.FLAG_ACTIVITY_NEW_TASK);
            (Intent.ACTION_VIEW);
            ((file), "application/-archive");
            startActivity(intent);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (())
                        ();
                    finish();
                }
            }, 10000);
        } else {
            (this, "安装出错,请重新下载", Toast.LENGTH_SHORT).show();
        }
    }