Android 模拟多线程下载

 以下是一个多线程下载的例子,见代码:

1、首先是布局文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent">
 5 
 6 
 7     <Button
 8         android:layout_width="wrap_content"
 9         android:layout_height="wrap_content"
10         android:text="下载"
11         android:id="@+id/btnDownLoad" />
12 
13     <TextView
14         android:layout_width="wrap_content"
15         android:layout_height="wrap_content"
16         android:text="New Text"
17         android:id="@+id/tv"
18         android:layout_gravity="center_vertical" />
19 </LinearLayout>

  2、然后是对应的Activity文件

 1 import android.app.Activity;
 2 import android.os.Handler;
 3 import android.os.Message;
 4 import android.os.Bundle;
 5 import android.view.View;
 6 import android.widget.Button;
 7 import android.widget.TextView;
 8 
 9 import com.yt.httpstudy.util.Download;
10 
11 
12 public class DownLoadActivity extends Activity {
13     private Button btnDown;
14     private TextView textView;
15     private int count = 0;
16     private Handler handler = new Handler(){
17         //接收信息并且处理
18         public void handleMessage(Message message){
19             int result = message.what;
20             count += result;
21            if(count ==3){
22                //下载完成后刷新页面
23                 textView.setText("下载完成!"+count);
24             }
25         }
26     };
27     @Override
28     protected void onCreate(Bundle savedInstanceState) {
29         super.onCreate(savedInstanceState);
30         setContentView(R.layout.activity_down_load);
31         btnDown = (Button) findViewById(R.id.btnDownLoad);
32         textView = (TextView) findViewById(R.id.tv);
33 
34         btnDown.setOnClickListener(new View.OnClickListener() {
35             @Override
36             public void onClick(View view) {
37 
38                 new Thread(){
39                     @Override
40                     public void run() {
41                         super.run();
42                         Download download = new Download(handler);
43                         //下载资源的地址
44                         download.downLoadFile("http://192.168.1.123:8080/test/asd.jpg");
45                     }
46                 }.start();
47             }
48         });
49     }
50 }

     3、处理多线程下载

  1 import android.os.Environment;
  2 import android.os.Handler;
  3 import android.os.Message;
  4 
  5 import java.io.File;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.io.RandomAccessFile;
  9 import java.net.HttpURLConnection;
 10 import java.net.MalformedURLException;
 11 import java.net.URL;
 12 import java.util.concurrent.Executor;
 13 import java.util.concurrent.Executors;
 14 
 15 /**
 16  * Created by
 17  */
 18 public class Download {
 19 
 20 
 21     public   Handler handler;
 22     //创建线程池
 23     private Executor threadPool = Executors.newFixedThreadPool(3);
 24 
 25     //构造器
 26     public Download(Handler handler){
 27         this.handler = handler;
 28     }
 29 
 30     //线程池对象
 31     static class DownLoadRunnable implements  Runnable{
 32         //指定成员变量
 33         private String url;
 34         private String fileName;
 35         private long start,end;
 36         private Handler handler;
 37 
 38         public DownLoadRunnable(String url,String fileName,long start,long end,Handler handler){
 39             this.url = url;
 40             this.fileName = fileName;
 41             this.start =  start;
 42             this.end = end;
 43             this.handler = handler;
 44 
 45         }
 46         @Override
 47         public void run() {
 48 
 49             HttpURLConnection conn = null;
 50             try {
 51                 URL httpUrl = new URL(url);
 52                 conn = (HttpURLConnection) httpUrl.openConnection();
 53                 conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
 54                 conn.setRequestMethod("GET");
 55                 conn.setReadTimeout(5000);
 56 
 57                 //往本地写文件
 58                 RandomAccessFile access = new RandomAccessFile(new File(fileName),"rwd");
 59                 access.seek(start);
 60                 //读取数据流
 61                 InputStream in = conn.getInputStream();
 62 
 63                 //创建缓冲区
 64                 byte[] b = new byte[1024*4];
 65                 int len = 0;
 66                 while ((len = in.read(b)) !=-1){
 67                     access.write(b,0,len);
 68                 }
 69                 if(access !=null){
 70                     access.close();
 71                 }
 72                 if(in !=null){
 73                     in.close();
 74                 }
 75 
 76                 //发送消息
 77                 Message message = new Message();
 78                 message.what =1;
 79                 handler.sendMessage(message);
 80             } catch (IOException e) {
 81                 e.printStackTrace();
 82             }
 83 
 84         }
 85     }
 86 
 87     public void downLoadFile(String url){
 88         try {
 89             URL httpUrl = new URL(url);
 90             HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
 91             conn.setRequestMethod("GET");
 92             conn.setReadTimeout(5000);
 93 
 94             //获取下载内容长度
 95             int count = conn.getContentLength();
 96             int bloack = count/3;
 97 
 98             //获取文件名
 99             String fileName = getFileName(url);
100 
101             //获取外部设备名称
102             File parent  = Environment.getExternalStorageDirectory();
103             File fileDownLoad = new File(parent,fileName);
104 
105             for(int i=0;i<3;i++){
106                 long start = i*bloack;
107                 long end = (i+1)*bloack-1;
108                 //第三个线程需要包括完最后的数据,否则不完整
109                 if(i==2){
110                     end = count;
111                 }
112 
113                 DownLoadRunnable runnable =
114                         new DownLoadRunnable(url,
115                                 fileDownLoad.getAbsolutePath(),
116                                 start,end,handler);
117                 //线程池提交任务
118                 threadPool.execute(runnable);
119             }
120         } catch (MalformedURLException e) {
121             e.printStackTrace();
122         } catch (IOException e) {
123             e.printStackTrace();
124         }
125     }
126 
127     //根据URL取出文件名
128     public String getFileName(String url){
129         return url.substring(url.lastIndexOf("/")+1);
130     }
131 }

 

posted @ 2015-08-27 20:48  黄海-1991  阅读(219)  评论(0编辑  收藏  举报