美文网首页
Android 下载文件(使用OKHttp)

Android 下载文件(使用OKHttp)

作者: 刘坤林 | 来源:发表于2019-11-22 14:23 被阅读0次

    添加相关OKHttp的依赖后,复制以下代码即可。

    final String url = "http://192.168.3.127:8081/aaaa.txt";

    final String fileName = "aaaa.txt";

    final long startTime = System.currentTimeMillis();

    OkHttpClient okHttpClient =new OkHttpClient();

    Request request =new Request.Builder()

    .url(url)

    .addHeader("Connection", "close")

    .build();

    okHttpClient.newCall(request).enqueue(new Callback() {

    @Override

        public void onFailure(Call call, IOException e) {

    Logger.e("@" + e.getMessage());

            closeloading();

            showShortToast("下载失败");

        }

    @Override

        public void onResponse(Call call, Response response)throws IOException {

    showloading("正在下载1%");

            InputStream is =null;

            byte[] buf =new byte[2048];

            int len =0;

            FileOutputStream fos =null;

            String savePath = Environment.getExternalStorageDirectory().getAbsolutePath(); // 储存下载文件的目录

            File filedir =new File(savePath);

            if (!filedir.exists()) {

    filedir.mkdir();

            }

    try {

    is = response.body().byteStream();

                long total = response.body().contentLength();

                File file =new File(savePath, fileName);

                if (file.exists()) {

    file.delete(); // 覆盖(删除原先的文件)

                }

    fos =new FileOutputStream(file);

                long sum =0;

                int oldProgress = -1;

                while ((len = is.read(buf)) != -1) {

    fos.write(buf, 0, len);

                    sum += len;

                    int progress = (int) (sum *1.0f / total *100);

                    if (oldProgress != progress) {

                            oldProgress = progress;

                            Logger.i("下载进度" + progress);

                            showloading("正在下载" + progress + "%");

                       }

                }

                fos.flush();

                closeloading();

                showShortToast("下载完成");

                Logger.i("下载完成,用时:" + (System.currentTimeMillis() -startTime));

    }catch (Exception e) {

    closeloading();

                showShortToast("下载失败");

                Logger.e("下载失败" + e.getMessage());

            }finally {

    try {

    if (is !=null) {

    is.close();

                    }

    }catch (IOException e) {

    Logger.e("11" + e.getMessage());

                }

    try {

    if (fos !=null) {

    fos.close();

                    }

    }catch (IOException e) {

    Logger.e("22" + e.getMessage());

                }

    }

    }

    });

    安装:注意Android7.0后和前的区别

    参考:https://blog.csdn.net/u010356768/article/details/89212742

    try {

    Intent intent =new Intent(Intent.ACTION_VIEW);

        File apkFile =new File(fullPath);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri uri = FileProvider.getUriForFile(getActivity(), *****+".provider", apkFile);

            intent.setDataAndType(uri, "application/vnd.android.package-archive");

        }else {

    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

        }

    startActivity(intent);

    }catch (Exception e) {

    Logger.e("无法安装" + e.getMessage());

    }

    相关文章

      网友评论

          本文标题:Android 下载文件(使用OKHttp)

          本文链接:https://www.haomeiwen.com/subject/tlonictx.html