在线咨询
微信咨询
服务热线
服务热线:15639912513
TOP
当前位置:
首页 > 新闻中心> 安卓课堂>android实现多线程下载实例

android实现多线程下载实例

发布时间:2020-02-05 浏览:3647次

android实现多线程下载代码如下。

布局类

adv_1.png

java代码如下

package cn.xhhkj.xhhkjtest;


import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.LinearLayout;

import android.widget.ProgressBar;


import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;


public class MainActivity extends Activity implements OnClickListener{


    private String path = "http://192.168.0.101/7z1900x64x3610.exe";

    private int threadCount = 4;

    private EditText et_url;

    private EditText et_count;

    private Button btn_down;

    private LinearLayout ll_progress;

    private int blockSize;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        et_url = (EditText) findViewById(R.id.et_url);

        et_count = (EditText) findViewById(R.id.et_count);

        btn_down = (Button) findViewById(R.id.btn_download);

        ll_progress = (LinearLayout) findViewById(R.id.ll_progress);


        btn_down.setOnClickListener(this);

    }


    @Override

    public void onClick(View v) {

        ll_progress.removeAllViews();

        String temp = et_count.getText().toString().trim();

        int count = Integer.parseInt(temp);

        for(int i= 0;i<count;i++){

            View.inflate(getApplicationContext(), R.layout.item, ll_progress);

        }

        new Thread(){

            public void run() {

                try {

                    URL url = new URL(path);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("GET");

                    connection.setConnectTimeout(10000);

                    int code = connection.getResponseCode();

                    if(code==200){

                        int length = connection.getContentLength();

                        RandomAccessFile file = new RandomAccessFile(getFileName(path), "rw");

                        file.setLength(length);

                        blockSize = length/threadCount;

                        for(int i =0;i<threadCount;i++){

                            int startIndex = i*blockSize;

                            int endIndex = (i+1)*blockSize-1;

                            if(i == threadCount-1){

                                endIndex = length-1;

                            }

                            ProgressBar pb = (ProgressBar) ll_progress.getChildAt(i);

                            pb.setMax(endIndex-startIndex);

                            new DownLoadThread(startIndex, endIndex, i).start();

                        }

                    }

                } catch (Exception e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            };

        }.start();

    }


    private class DownLoadThread extends Thread{

        private int startIndex;

        private int endIndex;

        private int threadID;

        private ProgressBar pb;


        public DownLoadThread(int startIndex, int endIndex, int threadID) {

            this.startIndex = startIndex;

            this.endIndex = endIndex;

            this.threadID = threadID;

            this.pb = (ProgressBar) ll_progress.getChildAt(threadID);

        }


        public void run() {

            try {

                File temp = new File(getFileName(path)+threadID+".log");

                if(temp!=null && temp.length()>0){

                    FileInputStream fis = new FileInputStream(temp);

                    BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

                    String result = reader.readLine();

                    startIndex = Integer.parseInt(result);

                }

                URL url = new URL(path);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("GET");

                connection.setConnectTimeout(10000);

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

                if(connection.getResponseCode()==206){

                    System.out.println("线程"+threadID+"开始下载"+startIndex);

                    InputStream inputStream = connection.getInputStream();

                    int len = -1;

                    byte[] buffer = new byte[1024*500];

                    RandomAccessFile file = new RandomAccessFile(getFileName(path), "rw");

                    file.seek(startIndex);

                    int count=0;

                    while((len=inputStream.read(buffer))!=-1){

                        file.write(buffer, 0, len);

                        count+=len;

                        int position = count+startIndex;

                        pb.setProgress(position-threadID*blockSize);

                        RandomAccessFile tempFile = new RandomAccessFile(getFileName(path)+threadID+".log", "rwd");

                        tempFile.write(String.valueOf(position).getBytes());

                    }

                    file.close();

                    inputStream.close();

                    System.out.println("线程"+threadID+"下载结束");

                    if(temp!=null){

                        temp.delete();

                    }

                }

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

    }

    private String getFileName(String path) {

        String[] result = path.split("/");

        return getCacheDir().getAbsolutePath()+"/"+result[result.length-1];

    }

}


 


TAG
3647
该内容对我有帮助