多线程下载

来源:互联网 发布:打电话不要钱的软件 编辑:程序博客网 时间:2024/05/01 01:46
Java:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private EditText weburl;
    private Button btn;
    private boolean flag = false;// false暂停下载true正在下载
    private int total = 0;// 已下载了的
    private File file;
    private int end;// 文件的总长度
    private List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>();
    private ProgressBar progressBar0;
    private Handler handler = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if (msg.what == 0x123) {
                if (msg.arg1 >= end) {
                    Toast.makeText(MainActivity.this, "下载完成", 1).show();
                }
                progressBar0.setProgress(msg.arg1);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        weburl = (EditText) findViewById(R.id.weburl1);
        btn = (Button) findViewById(R.id.uploadbut1);
        progressBar0 = (ProgressBar) findViewById(R.id.prog1);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (flag) {
            flag = false;
            btn.setText("下载");
            return;
        }
        flag = true;
        btn.setText("暂停");
        if (total == 0) {
            new Thread() {
                public void run() {
                    try {
                        file = new File(
                                Environment.getExternalStorageDirectory()
                                        + "/file", getFileName(weburl.getText()
                                        .toString()));
                        URL url = new URL(weburl.getText().toString());
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        conn.setConnectTimeout(5000);
                        end = conn.getContentLength();// 获取文件的长度
                        progressBar0.setMax(end);
                        Log.e("TAG", "length:" + end + "=====");
                        RandomAccessFile accessFile = new RandomAccessFile(
                                file, "rw");
                        accessFile.setLength(end);// 设置文件的长度
                        int addload = end / 4;
                        for (int i = 0; i < 4; i++) {
                            int start = i * addload;
                            int over = (i + 1) * addload;
                            if (i == 3) {
                                over = end;
                            }
                            Map<String, Integer> map = new HashMap<String, Integer>();
                            map.put("start", start);
                            map.put("over", over);
                            map.put("finished", 0);
                            list.add(map);
                            Thread thread = new Thread(new DownLoadd(start,
                                    over, file, i));
                            thread.start();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                };
            }.start();
        } else {
            // 续传
            for (int j = 0; j < list.size(); j++) {
                Thread thread = new Thread(new DownLoadd(list.get(j).get(
                        "start")
                        + list.get(j).get("finished"), list.get(j).get("over"),
                        file, j));
                thread.start();
            }

        }
    }

    class DownLoadd implements Runnable {
        private int begin;// 请求数据的其实位置
        private int end;// 请求的结束位置
        private File file;
        private int id;

        DownLoadd(int begin, int end, File file, int id) {
            this.begin = begin;
            this.end = end;
            this.file = file;
            this.id = id;
        }

        public void run() {
            try {
                URL url = new URL(weburl.getText().toString());
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Range", "bytes=" + begin + "-" + end);
                RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
                accessFile.seek(begin);
                InputStream is = conn.getInputStream();
                int len;
                byte[] b = new byte[1024 * 1024];
                while ((len = is.read(b)) != -1 && flag) {
                    accessFile.write(b, 0, len);
                    list.get(id).put("finished",
                            list.get(id).get("finished") + len);
                    addFinshed(len);
                }
                accessFile.close();
                is.close();
                conn.disconnect();

            } catch (Exception e) {
                Log.e("url", "url异常");
                e.printStackTrace();
            }
        }

    }

    synchronized private void addFinshed(int len) {
        total += len;// 记录已下载的总长度
        Log.e("TAG", "已完成:" + total);
        // 发一个数据
        handler.obtainMessage(0x123, total, 0).sendToTarget();
    }

    // 获取下载文件的文件名
    private String getFileName(String url) {
        int index = url.lastIndexOf("/") + 1;
        return url.substring(index);
    }
}
----------------------------------------------------------------------
xml:
<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=".MainActivity" >

    <EditText
        android:id="@+id/weburl1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:text="http://192.168.43.74:8080/Download/File/Beyond.mp3" />

    <Button
        android:id="@+id/uploadbut1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始下载" />

    <ProgressBar
        android:id="@+id/prog1"
        style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:progressDrawable="@drawable/layer_0" />

    <TextView
        android:id="@+id/jindu_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textColor="#f00" />

</LinearLayout>

0 0
原创粉丝点击