Android——单、多线程下载

/**
*用于打开用于下载的界面.
*/
package com.example.administrator.myconnection;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

/**
 * Created by Administrator on 2015/9/11.
 */
public class IndexActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mBtnUrlConnection;
    private Button mBtnDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        setContentView(R.layout.activity_index);
        mBtnUrlConnection= (Button) findViewById(R.id.btn_urlconnect);
        mBtnDownload= (Button) findViewById(R.id.btn_download);
        mBtnUrlConnection.setOnClickListener(this);
        mBtnDownload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_connect:
                break;
            case R.id.btn_download:
                Intent intent=new Intent("com.example.administrator.myconnection.DownloadActivity");
                startActivity(intent);
                break;
        }
    }
}
/**
*下载界面
*/
package com.example.administrator.myconnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2015/9/11.
 */
public class DownloadActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mBtnSingleDownload;
    private Button mBtnMoreDownload;
    private ProgressBar progressBar;
    int length;
    /**
     * 当Handler被创建会关联到创建它的当前线程的消息队列,该类用于往消息队列发送消息
    * 消息队列中的消息由当前线程内部进行处理
    */
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x23:
                    progressBar.setProgress(msg.arg1*100/length);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        progressBar= (ProgressBar) findViewById(R.id.progressbar);
        mBtnSingleDownload= (Button) findViewById(R.id.singledownload);
        mBtnMoreDownload= (Button) findViewById(R.id.multidownload);
        mBtnMoreDownload.setOnClickListener(this);
        mBtnSingleDownload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.singledownload:
                //单线程下载
              new Singledownload().execute();

                break;
            case R.id.multidownload:
                //多线程下载
                multiDownload();
                break;
        }

    }

    private void multiDownload() {  //多线程下载
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //下载文件的地址
                    String urlPath="http://192.168.0.30:8080/MyWebTest/music/aa.mp3";
                    URL url = new URL(urlPath);
                    URLConnection connection=url.openConnection();
                    //获取下载文件的长度
                    length=connection.getContentLength();
                    //在本地新建的文件地址,保存下载的文件
                    File file=new File(Environment.getExternalStorageDirectory(),"cc.mp3");
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    //分成5个线程并设置每个线程下载的起始、结束位置
                    MultiThread[] threads=new MultiThread[5];
                    for (int i=0;i<5;i++){
                        MultiThread thread=null;
                        if(i==4){
                            thread = new MultiThread(length / 5*4, length , urlPath, file.getAbsolutePath());
                        }else {
                            thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath());
                        }
                        thread.start();
                        threads[i]=thread;
                    }
                    boolean isFinish=true;
                    while(isFinish){
                        int sum=0;
                        for (MultiThread thread:threads){
                            sum+= thread.getSum();
                        }
                        Message msg=  handler.obtainMessage();
                        msg.what=0x23;
                        msg.arg1=sum;
                        handler.sendMessage(msg);
                        if(sum+10>=length){
                            isFinish=false;
                        }
                        Thread.sleep(1000);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    class Singledownload extends AsyncTask<String,Integer,String>{

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress((int) (values[0]*100.0/values[1]));
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                URL url=new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3");
                URLConnection connection=url.openConnection();
                int length=connection.getContentLength();
                InputStream is=connection.getInputStream();
                File file=new File(Environment.getExternalStorageDirectory(),"aa.mp3");
                if (!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream os=new FileOutputStream(file);
                byte[] array=new byte[1024];
                int sum=0;
                int index=is.read(array);
                while (index!=-1){
                    os.write(array,0,index);
                    sum+=index;
                    publishProgress(sum,length);
                    index=is.read(array);
                }
                is.close();
                os.flush();
                os.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
/**
*多线程下载的线程
*/
package com.example.administrator.myconnection;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by zhonghangIT on 2015/9/11.
 */
public class MultiThread extends Thread{
    public MultiThread(long start, long end, String url, String filePath) {//传入开始位置,结束位置,下载路径,保存文件路径
        this.start = start;
        this.end = end;
        this.urlPath = url;
        this.filePath = filePath;
    }
    private int sum=0;
    private long start;
    private long end;
    private String urlPath;
    private String filePath;
    public int getSum() {
        return sum;
    }

    @Override
    public void run() {
        try {
            URL url=new URL(urlPath);
            URLConnection connection=url.openConnection();
            //allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
            connection.setAllowUserInteraction(true);
            connection.setRequestProperty("Range", "bytes=" + start + "-"
                    + end);
             InputStream is= connection.getInputStream();
            byte [] array=new byte[1024];
            is.read(array);

            File file=new File(filePath);
            //RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,
            // 并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件。
            RandomAccessFile randomAccessFileile=new RandomAccessFile(file,"rw");
            randomAccessFileile.seek(start); //找到下载的起始位置
            int index=is.read(array);
            while (index!=-1){
                    randomAccessFileile.write(array,0,index);
                    sum+=index;
                    index=is.read(array);
            }
            randomAccessFileile.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值