温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android怎么实现文件下载功能

发布时间:2021-09-13 18:12:37 来源:亿速云 阅读:212 作者:chen 栏目:开发技术

这篇文章主要讲解了“Android怎么实现文件下载功能”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Android怎么实现文件下载功能”吧!

权限

<!--  文件读写权限  -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--  访问内存  -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

DownloadOkHttp 使用(无显示)

下载完成地址: /storage/emulated/0/小红书/xiaohongshu.apk

DownloadUtil.DownloadOkHttp.get().download(apk, Environment.getExternalStorageDirectory() + "/" + "小红书", new DownloadUtil.DownloadOkHttp.OnDownloadListener() {
    @Override
    public void onDownloadSuccess() {
      Log.e("下载","成功");
                }

              @Override
                      public void onDownloading(int progress) {
                       Log.e("下载", String.valueOf(progress));
                         }

                    @Override
                   public void onDownloadFailed() {
                   Log.e("下载","失败");
         }
 });

Download 使用(有显示)

下载完成地址: /小红书/小红书.apk

new DownloadUtil.Download(this, apk, "小红书.apk", "小红书");

dialog_progress

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/dp_20"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/id_progress"
        
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:id="@+id/id_text"
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:gravity="right"
        android:text="0 %"
        android:layout_height="wrap_content"/>

</LinearLayout>

**工具类DownloadUtil(两个实现方法,自己悟!!!)

package com.simon.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.simon.app.R;

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 androidx.annotation.NonNull;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建者: Simon
 * 创建时间:2021/6/7 13:58
 * 描述:文件下载
 */

public class DownloadUtil {

    public static class DownloadOkHttp {

        private static DownloadOkHttp downloadUtil;
        private final OkHttpClient okHttpClient;

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

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

        /**
         *
         * @param url 下载连接
         * @param saveDir 储存下载文件的SDCard目录
         * @param listener 下载监听
         */
        public void download( String url, final String saveDir, final OnDownloadListener listener) {
            Request request = new Request.Builder().url(url).build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    // 下载失败
                    listener.onDownloadFailed();
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    // 储存下载文件的目录
                    String savePath = isExistDir(saveDir);
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        File file = new File(savePath, getNameFromUrl(url));
                        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();
                    } catch (Exception e) {
                        listener.onDownloadFailed();
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }
                }
            });
        }

        /**
         * 判断下载目录是否存在
         * @param saveDir
         * @return
         * @throws IOException
         */
        private String isExistDir(String saveDir) throws IOException {
            // 下载位置
            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            return savePath;
        }

        /**
         *  url
         * 从下载连接中解析出文件名
         */
        @NonNull
        public static String getNameFromUrl(String url) {
            return url.substring(url.lastIndexOf("/") + 1);
        }

        public interface OnDownloadListener {
            /**
             * 下载成功
             */
            void onDownloadSuccess();

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

            /**
             * 下载失败
             */
            void onDownloadFailed();
        }
    }

    public static class Download {

        private String fileSavePath = "";//保存文件的本地路径
        private String fileDownLoad_path = "";//下载的URL
        private String mfileName = "";//下载的文件名字
        private boolean mIsCancel = false;
        private int mProgress;
        private ProgressBar mProgressBar;
        private TextView text;
        private Dialog mDownloadDialog;
        private final Context context;

        private static final int DOWNLOADING = 1;
        private static final int DOWNLOAD_FINISH = 2;

        private Handler mUpdateProgressHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case DOWNLOADING:
                        // 设置进度条
                        mProgressBar.setProgress(mProgress);
                        text.setText(String.valueOf(mProgress));
                        break;
                    case DOWNLOAD_FINISH:
                        // 隐藏当前下载对话框
                        mDownloadDialog.dismiss();
                }
            }
        };

        /**
         * 下载初始化
         * @param context 上下文
         * @param fileDownLoad_path 下载的URL
         * @param mfileName 下载的文件名字
         * @param fileSavePath 保存文件的本地路径
         */
        public Download(Context context, String fileDownLoad_path, String mfileName, String fileSavePath) {
            this.context = context;
            this.fileDownLoad_path = fileDownLoad_path;
            this.mfileName = mfileName;
            this.fileSavePath = Environment.getExternalStorageDirectory() + "/" + fileSavePath;
            showDownloadDialog();
        }

        /**
         * 显示正在下载的对话框
         */
        protected void showDownloadDialog() {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("下载中");
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
            mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
            text = view.findViewById(R.id.id_text);
            builder.setView(view);

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 隐藏当前对话框
                    dialog.dismiss();
                    // 设置下载状态为取消
                    mIsCancel = true;
                }
            });

            mDownloadDialog = builder.create();
            mDownloadDialog.show();

            // 下载文件
            downloadFile();
        }

        /**
         * 下载文件
         */
        private void downloadFile() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            File dir = new File(fileSavePath);
                            if (!dir.exists()){
                                dir.mkdirs();
                            }
                            // 下载文件
                            HttpURLConnection conn = (HttpURLConnection) new URL(fileDownLoad_path).openConnection();
                            conn.connect();
                            InputStream is = conn.getInputStream();
                            int length = conn.getContentLength();

                            File apkFile = new File(fileSavePath, mfileName);
                            FileOutputStream fos = new FileOutputStream(apkFile);

                            int count = 0;
                            byte[] buffer = new byte[1024];
                            while (!mIsCancel) {
                                int numread = is.read(buffer);
                                count += numread;
                                // 计算进度条当前位置
                                mProgress = (int) (((float) count / length) * 100);
                                // 更新进度条
                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);

                                // 下载完成
                                if (numread < 0) {
                                    mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                                    break;
                                }
                                fos.write(buffer, 0, numread);
                            }
                            fos.close();
                            is.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}

感谢各位的阅读,以上就是“Android怎么实现文件下载功能”的内容了,经过本文的学习后,相信大家对Android怎么实现文件下载功能这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI