美文网首页
android 手机版断点续传实现

android 手机版断点续传实现

作者: yanghanbin_it | 来源:发表于2017-06-08 15:00 被阅读0次

同理,只需要把第十九课的代码搬至android代码中改造一下即可完成,且完善进度条功能

public class MainActivity extends Activity {

    int ThreadCount = 4;

    String fileName = "nopad.zip";

    String path = "http://192.168.1.103:8080/android/" + fileName;

    int finishedThread = 0;

    int currentProgress;

    ProgressBar pb;

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                Toast.makeText(MainActivity.this, "下载完成了", 0).show();
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb = (ProgressBar) findViewById(R.id.pb);
    }

    public void startDown(View v) {
        currentProgress = 0;
        Toast.makeText(this, "开始下载了", 0).show();
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);

                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setReadTimeout(5000);
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);

                    if (conn.getResponseCode() == 200) {
                        // 1.先获取请求资源的大小
                        int length = conn.getContentLength();

                        pb.setMax(length); // 设置进度条的最大值

                        File file = new File(
                                Environment.getExternalStorageDirectory(),
                                fileName);
                        // 生成临时文件
                        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                        // 设置临时文件的大小
                        raf.setLength(length);
                        raf.close();
                        // 计算每个线程应该要下载多少个字节
                        int size = length / ThreadCount;

                        for (int i = 0; i < ThreadCount; i++) {
                            // 计算线程下载的开始位置和结束位置
                            int startIndex = i * size;
                            int endIndex = (i + 1) * size - 1;
                            // 如果是最后一个线程,那么结束位置写死
                            if (i == (ThreadCount - 1)) {
                                endIndex = length - 1;
                            }
                            new DownThread(startIndex, endIndex, i).start();
                        }
                    }
                } catch (IOException e) {
                }
            }
        };
        t.start();
    }

    class DownThread extends Thread {

        int startIndex;
        int endIndex;
        int threadId;

        public DownThread(int startIndex, int endIndex, int threadId) {
            super();
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            this.threadId = threadId;
        }

        @Override
        public void run() {
            // 再次发送HTTP请求,下载源文件
            try {
                // 生成一个专门用来记录下载进度的临时文件
                File progressFile = new File(
                        Environment.getExternalStorageDirectory(), threadId
                                + ".txt");
                if (progressFile.exists()) {
                    FileInputStream fis = new FileInputStream(progressFile);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(fis));
                    int lastProgress = Integer.parseInt(br.readLine());
                    // 从进度临时文件中读取出上一次下载的总进度,然后与原本的开始位置相加,得到新的开始位置
                    startIndex += lastProgress;
                    currentProgress += lastProgress;
                    pb.setProgress(currentProgress);
                    fis.close();
                }

                URL url = new URL(path);

                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);

                System.out.println("线程threadId" + threadId + "下载区间:"
                        + startIndex + "-" + endIndex);

                // 设置请求的数据的区间
                conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
                        + endIndex);

                // 请求部分数据,响应码为206
                if (conn.getResponseCode() == 206) {
                    // 此时只有 1/threadcount数据
                    InputStream is = conn.getInputStream();
                    byte[] b = new byte[1024];
                    int len = 0;
                    long total = 0;
                    File file = new File(
                            Environment.getExternalStorageDirectory(), fileName);
                    // 这样可以保证数据同步写入硬盘中,防止停电等原因da
                    RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                    // 把文件的写入位置移动至startIndex
                    raf.seek(startIndex);
                    while ((len = is.read(b)) != -1) {
                        // 每次读取流里的数据写入临时文件
                        raf.write(b, 0, len);
                        total += len;

                        currentProgress += len;

                        pb.setProgress(currentProgress);

                        System.out.println("线程" + threadId + " 下载了:" + total);

                        RandomAccessFile progressRaf = new RandomAccessFile(
                                progressFile, "rwd");
                        progressRaf.write((total + "").getBytes());
                        progressRaf.close();
                    }
                    raf.close();
                    progressFile.delete(); // 下载完成后,将临时文件删除

                    ++finishedThread;

                    synchronized (path) {
                        if (finishedThread == ThreadCount) {
                            handler.sendEmptyMessage(0);
                            for (int i = 0; i < ThreadCount; i++) {
                                File f = new File(
                                        Environment
                                                .getExternalStorageDirectory(),
                                        i + ".txt");
                                f.delete();
                            }
                            finishedThread = 0;
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.multidown.MainActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startDown"
        android:text="开始下载" />

    <ProgressBar
        android:id="@+id/pb"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>  

效果图:
[图片上传中。。。(1)]

相关文章

网友评论

      本文标题:android 手机版断点续传实现

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