android 利用okhttp实现apk下载,带进度

下载类

 /**
     * 文件下载
     *
     * @param url 下载的连接
     */
    public void downFile(String url) {
        ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle(getResources().getString(R.string.s_ing_download));
        progressDialog.setMessage(getResources().getString(R.string.s_please_wait));
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.show();
        progressDialog.setCancelable(false);
        DownloadUtil.get().download(url, Environment.getExternalStorageDirectory().getAbsolutePath() + "/apk/", "apk.apk", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                //下载完成进行相关逻辑操作
                Log.e("====", "=======>" + file.getPath());
              
            }

            @Override
            public void onDownloading(int progress) {
                progressDialog.setProgress(progress);
            }

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

下载的工具类

/**
 * 文件下载工具类(单例模式)
 *
 */

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) {


        File f1 = new File(destFileDir,destFileName);
        if (f1.exists()){
            f1.delete();
        }


        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(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 (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中更新进度条
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

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

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

        /**
         * @param e 下载异常信息
         */
        void onDownloadFailed(Exception e);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中使用OkHttp下载和安装APK文件的过程如下: 1、首先需要添加OkHttp库的依赖项,可以在项目的build.gradle文件中添加以下代码: ``` implementation 'com.squareup.okhttp3:okhttp:x.x.x' ``` 其中,x.x.x为OkHttp库的版本号。 2、在代码中创建OkHttpClient对象并构建下载请求。例如: ``` OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(apkUrl) // APK文件的URL地址 .build(); ``` 3、发送请求并获取响应结果。可以使用OkHttpClient的newCall()方法发送请求,并使用enqueue()方法异步获取响应结果。例如: ``` client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下载失败处理逻辑 } @Override public void onResponse(Call call, Response response) throws IOException { // 获取响应的输入流 InputStream inputStream = response.body().byteStream(); // 创建文件输出流 FileOutputStream outputStream = new FileOutputStream(apkFilePath); // 将输入流写入文件输出流中 byte[] buffer = new byte[2048]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } // 关闭输入流和输出流 inputStream.close(); outputStream.close(); // 在下载完成后进行APK安装 installApk(apkFilePath); } }); ``` 在上述代码中,需要自行实现installApk()方法,用于执行APK的安装操作。这可以通过调用Intent进行安装,例如: ``` private void installApk(String apkFilePath) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(apkFilePath)), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } ``` 以上就是使用OkHttp进行APK文件下载和安装的基本步骤。需要注意的是,下载和安装APK文件需要在AndroidManifest.xml文件中添加相关权限,例如: ``` <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值