Android之多线程断点下载

本文主要包含多线程下载的一些简单demo,包括三部分

  1. java实现
  2. android实现
  3. XUtils开源库实现

注意下载添加网络权限与SD卡读写权限

java实现多线程下载

public class MutileThreadDownload {
    /**
     * 线程的数量
     */
    private static int threadCount = 3;

    /**
     * 每个下载区块的大小
     */
    private static long blocksize;

    /**
     * 正在运行的线程的数量
     */
    private static int runningThreadCount;

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 服务器文件的路径
        String path = "http://192.168.1.100:8080/ff.exe";
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        int code = conn.getResponseCode();
        if (code == 200) {
            long size = conn.getContentLength();// 得到服务端返回的文件的大小
            System.out.println("服务器文件的大小:" + size);
            blocksize = size / threadCount;
            // 1.首先在本地创建一个大小跟服务器一模一样的空白文件。
            File file = new File("temp.exe");
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.setLength(size);
            // 2.开启若干个子线程分别去下载对应的资源。
            runningThreadCount = threadCount;
            for (int i = 1; i <= threadCount; i++) {
                long startIndex = (i - 1) * blocksize;
                long endIndex = i * blocksize - 1;
                if (i == threadCount) {
                    // 最后一个线程
                    endIndex = size - 1;
                }
                System.out.println("开启线程:" + i + "下载的位置:" + startIndex + "~"
                        + endIndex);
                new DownloadThread(path, i, startIndex, endIndex).start();
            }
        }
        conn.disconnect();
    }

    private static class DownloadThread extends Thread {
        private int threadId;
        private long startIndex;
        private long endIndex;
        private String path;

        public DownloadThread(String path, int threadId, long startIndex,
                long endIndex) {
            this.path = path;
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
        }

        @Override
        public void run() {
            try {
                // 当前线程下载的总大小
                int total = 0;
                File positionFile = new File(threadId + ".txt");
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setRequestMethod("GET");
                // 接着从上一次的位置继续下载数据
                if (positionFile.exists() && positionFile.length() > 0) {// 判断是否有记录
                    FileInputStream fis = new FileInputStream(positionFile);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(fis));
                    // 获取当前线程上次下载的总大小是多少
                    String lasttotalstr = br.readLine();
                    int lastTotal = Integer.valueOf(lasttotalstr);
                    System.out.println("上次线程" + threadId + "下载的总大小:"
                            + lastTotal);
                    startIndex += lastTotal;
                    total += lastTotal;// 加上上次下载的总大小。
                    fis.close();
                }

                conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
                        + endIndex);
                conn.setConnectTimeout(5000);
                int code = conn.getResponseCode();
                System.out.println("code=" + code);
                InputStream is = conn.getInputStream();
                File file = new File("temp.exe");
                RandomAccessFile raf = new RandomAccessFile(file, "rw");
                // 指定文件开始写的位置。
                raf.seek(startIndex);
                System.out.println("第" + threadId + "个线程:写文件的开始位置:"
                        + String.valueOf(startIndex));
                int len = 0;
                byte[] buffer = new byte[512];
                while ((len = is.read(buffer)) != -1) {
                    RandomAccessFile rf = new RandomAccessFile(positionFile,
                            "rwd");
                    raf.write(buffer, 0, len);
                    total += len;
                    rf.write(String.valueOf(total).getBytes());
                    rf.close();
                }
                is.close();
                raf.close();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 只有所有的线程都下载完毕后 才可以删除记录文件。
                synchronized (MutileThreadDownload.class) {
                    System.out.println("线程" + threadId + "下载完毕了");
                    runningThreadCount--;
                    if (runningThreadCount < 1) {
                        System.out.println("所有的线程都工作完毕了。删除临时记录的文件");
                        for (int i = 1; i <= threadCount; i++) {
                            File f = new File(i + ".txt");
                            System.out.println(f.delete());
                        }
                    }
                }

            }
        }
    }
}

安卓实现

public class MainActivity extends Activity {
    protected static final int DOWNLOAD_ERROR = 1;
    private static final int THREAD_ERROR = 2;
    public static final int DWONLOAD_FINISH = 3;
    private EditText et_path;
    private EditText et_count;
    /**
     * 存放进度条的布局
     */
    private LinearLayout ll_container;

    /**
     * 进度条的集合
     */
    private List<ProgressBar> pbs;

    /**
     * android下的消息处理器,在主线程创建,才可以更新ui
     */
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWNLOAD_ERROR:
                Toast.makeText(getApplicationContext(), "下载失败", 0).show();
                break;
            case THREAD_ERROR:
                Toast.makeText(getApplicationContext(), "下载失败,请重试", 0).show();
                break;
            case DWONLOAD_FINISH:
                Toast.makeText(getApplicationContext(), "下载完成", 0).show();
                break;
            }
        };
    };

    /**
     * 线程的数量
     */
    private int threadCount = 3;

    /**
     * 每个下载区块的大小
     */
    private long blocksize;

    /**
     * 正在运行的线程的数量
     */
    private  int runningThreadCount;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        et_count = (EditText) findViewById(R.id.et_count);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);
    }

    /**
     * 下载按钮的点击事件
     * @param view
     */
    public void downLoad(View view){
        //下载文件的路径
        final String path = et_path.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "对不起下载路径不能为空", 0).show();
            return;
        }
        String count = et_count.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "对不起,线程数量不能为空", 0).show();
            return;
        }
        threadCount = Integer.parseInt(count);
        //清空掉旧的进度条
        ll_container.removeAllViews();
        //在界面里面添加count个进度条
        pbs = new ArrayList<ProgressBar>();
        for(int j=0;j<threadCount;j++){
            ProgressBar pb = (ProgressBar) View.inflate(this, R.layout.pb, null);
            ll_container.addView(pb);
            pbs.add(pb);
        }
        Toast.makeText(this, "开始下载", 0).show();
        new Thread(){
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        long size = conn.getContentLength();// 得到服务端返回的文件的大小
                        System.out.println("服务器文件的大小:" + size);
                        blocksize = size / threadCount;
                        // 1.首先在本地创建一个大小跟服务器一模一样的空白文件。
                        File file = new File(Environment.getExternalStorageDirectory(),getFileName(path));
                        RandomAccessFile raf = new RandomAccessFile(file, "rw");
                        raf.setLength(size);
                        // 2.开启若干个子线程分别去下载对应的资源。
                        runningThreadCount = threadCount;
                        for (int i = 1; i <= threadCount; i++) {
                            long startIndex = (i - 1) * blocksize;
                            long endIndex = i * blocksize - 1;
                            if (i == threadCount) {
                                // 最后一个线程
                                endIndex = size - 1;
                            }
                            System.out.println("开启线程:" + i + "下载的位置:" + startIndex + "~"
                                    + endIndex);
                            int threadSize = (int) (endIndex - startIndex);
                            pbs.get(i-1).setMax(threadSize);
                            new DownloadThread(path, i, startIndex, endIndex).start();
                        }
                    }
                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = DOWNLOAD_ERROR;
                    handler.sendMessage(msg);
                }

            };
        }.start();

    }
    private class DownloadThread extends Thread {

        private int threadId;
        private long startIndex;
        private long endIndex;
        private String path;

        public DownloadThread(String path, int threadId, long startIndex,
                long endIndex) {
            this.path = path;
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
        }

        @Override
        public void run() {
            try {
                // 当前线程下载的总大小
                int total = 0;
                File positionFile = new File(Environment.getExternalStorageDirectory(),getFileName(path)+threadId + ".txt");
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setRequestMethod("GET");
                // 接着从上一次的位置继续下载数据
                if (positionFile.exists() && positionFile.length() > 0) {// 判断是否有记录
                    FileInputStream fis = new FileInputStream(positionFile);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(fis));
                    // 获取当前线程上次下载的总大小是多少
                    String lasttotalstr = br.readLine();
                    int lastTotal = Integer.valueOf(lasttotalstr);
                    System.out.println("上次线程" + threadId + "下载的总大小:"
                            + lastTotal);
                    startIndex += lastTotal;
                    total += lastTotal;// 加上上次下载的总大小。
                    fis.close();
                    //存数据库。
                    //_id path threadid total
                }

                conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
                        + endIndex);

                conn.setConnectTimeout(5000);
                int code = conn.getResponseCode();
                System.out.println("code=" + code);
                InputStream is = conn.getInputStream();
                File file = new File(Environment.getExternalStorageDirectory(),getFileName(path));
                RandomAccessFile raf = new RandomAccessFile(file, "rw");
                // 指定文件开始写的位置。
                raf.seek(startIndex);
                System.out.println("第" + threadId + "个线程:写文件的开始位置:"
                        + String.valueOf(startIndex));
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    RandomAccessFile rf = new RandomAccessFile(positionFile,
                            "rwd");
                    raf.write(buffer, 0, len);
                    total += len;
                    rf.write(String.valueOf(total).getBytes());
                    rf.close();
                    pbs.get(threadId-1).setProgress(total);
                }
                is.close();
                raf.close();

            } catch (Exception e) {
                e.printStackTrace();
                Message msg = Message.obtain();
                msg.what = THREAD_ERROR;
                handler.sendMessage(msg);
            } finally {
                // 只有所有的线程都下载完毕后 才可以删除记录文件。
                synchronized (MainActivity.class) {
                    System.out.println("线程" + threadId + "下载完毕了");
                    runningThreadCount--;
                    if (runningThreadCount < 1) {
                        System.out.println("所有的线程都工作完毕了。删除临时记录的文件");
                        for (int i = 1; i <= threadCount; i++) {
                            File f = new File(Environment.getExternalStorageDirectory(),getFileName(path)+ i + ".txt");
                            System.out.println(f.delete());
                        }
                        Message msg = Message.obtain();
                        msg.what = DWONLOAD_FINISH;
                        handler.sendMessage(msg);
                    }
                }

            }
        }
    }
    //http://192.168.1.100:8080/aa.exe
    private String getFileName(String path){
        int start = path.lastIndexOf("/")+1;
        return path.substring(start);
    }

}

利用XUtils开源框架实现,需要XUtils的jar包

public class MainActivity extends Activity {
    private EditText et_path;
    private TextView tv_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        tv_info = (TextView) findViewById(R.id.tv_info);
    }

    public void download(View view){
        String path = et_path.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "请输入下载的路径", 0).show();
            return;
        }else{
            HttpUtils http = new HttpUtils();
            HttpHandler handler = http.download(path,
                    "/sdcard/xxx.zip",
                    true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                    true, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
                    new RequestCallBack<File>() {

                        @Override
                        public void onStart() {
                            tv_info.setText("conn...");
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
                            tv_info.setText(current + "/" + total);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<File> responseInfo) {
                            tv_info.setText("downloaded:" + responseInfo.result.getPath());
                        }
                        @Override
                        public void onFailure(HttpException error, String msg) {
                            tv_info.setText(msg);
                        }
                });
        }
    }
}

完成

转载于:https://www.cnblogs.com/jjx2013/p/6223718.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
Android 的集合类主要包括 List、Set、Map 等,它们都是用来存储数据的。List 是有序的集合,可以存储重复的元素;Set 是无序的集合,不允许存储重复的元素;Map 是一种键值对存储的数据结构,可以通过键来获取值。 Android 的 IO 流主要用来进行文件的读写操作。Java 中的 IO 流主要分为字节流和字符流。字节流主要用来操作二进制文件,字符流主要用来操作文本文件。在 Android 中,FileInputStream 和 FileOutputStream 是字节流,用于读写二进制文件;FileReader 和 FileWriter 是字符流,用于读写文本文件。 Android多线程编程可以使用 Java 中的 Thread 类来实现。但是在 Android 中,应该使用异步任务 AsyncTask 来进行多线程编程。这是因为在 Android 中,主线程负责界面的绘制和事件响应,如果在主线程中进行耗时操作,会导致界面卡顿,用户体验不好。而 AsyncTask 可以在后台线程中执行耗时操作,同时也可以更新 UI。 Android断点上传下载一般使用 HttpURLConnection 来实现。在上传文件时,可以使用 HttpURLConnection 的 setChunkedStreamingMode 方法来进行分块上传,从而支持断点续传。在下载文件时,可以使用 HttpURLConnection 获取输入流,然后使用 RandomAccessFile 进行随机访问,从而实现断点续传。 Android 的线程池可以使用 Java 中的 Executor 和 ExecutorService 接口来实现。可以通过 ThreadPoolExecutor 类来创建线程池。线程池可以有效地利用线程资源,提高程序的效率。同时也可以控制线程的数量,避免线程数量过多导致程序崩溃。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值