Chinaunix首页 | 论坛 | 博客
  • 博客访问: 78719
  • 博文数量: 8
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 599
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-27 16:46
个人简介

哎……马上就要毕业了!求工作啊^0^

文章分类

全部博文(8)

文章存档

2013年(8)

我的朋友

分类: Android平台

2013-08-29 00:19:31

实现多线程下载的大概思路:(假设文件大小是6M,共有三条线程同时执行)

●首先要根据访问的URL路径去调用openConnection方法,得到HttpUrlConnection对象,HttpUrlConnection对象调用它的方法得到下载文件的长度,然后设置本地文件的长度。

点击(此处)折叠或打开

  1. int length = HttpURLConnection.getContentLength();
  2. RandomAccessFile file = new RandomAccessFile("calendar_setup.exe","rw");
  3. file.setLength(length);
        RandomAccessFile和File的区别:
             RandomAccessFile同时将FileInputStream和FileOutputStream整合到一起,而且支持将从文件任意字节处都或写数据;File类只是将文件作为整体来处理文件,不能读写文件

  ●根据文件长度和线程数计算每条线程下载的数据长度和下载位置,如文件长度为6M,线程数为3,那么每条线程下载数据的长度为2M,

                                                                 
       问题:在下载时如何指定这些线程开始下载的位置?→HTTP协议

  ●使用HTTP的Range头字段指定每条线程从文件的什么位置开始下载,如指定从文件的2M位置开始下载:

点击(此处)折叠或打开

  1. HttpURLConnection.setRequestProperty("Range","bytes=2097152-");
        设置请求头Range字段,就是bytes=2097152,2MB的字节,比如上图的线程2,在下载的过程中只要设置了这个头,那么它就会从线程1和线程3开始下载

  ●保存文件,使用RandomAccessFile类指定每条线程从本地的什么位置开始写入数据

 

点击(此处)折叠或打开

  1. RandomAccessFile file = new RandomAccessFile("calendar_setup.exe","rw");
  2. file.seek(2097152);

小案例:

 ●编写布局文件,主要有一个进度条,一个Button,一个EditText


点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android=""
  3.     android:orientation="vertical"
  4.     android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent"
  6.     >
  7. <TextView
  8.     android:layout_width="fill_parent"
  9.     android:layout_height="wrap_content"
  10.     android:text="下载"
  11.     />
  12. <EditText
  13.     android:layout_width="fill_parent"
  14.     android:layout_height="wrap_content"
  15.     android:hint="请输入下载路径"
  16.     android:text=""
  17.     android:id = "@+id/et_path"/>
  18. <ProgressBar
  19.     android:id="@+id/bar"
  20.     style="?android:attr/progressBarStyleHorizontal"
  21.     android:layout_width="fill_parent"
  22.     android:layout_height="wrap_content"/>
  23.  <TextView
  24.     android:id="@+id/tv_process"
  25.     android:layout_width="fill_parent"
  26.     android:layout_height="wrap_content"/>
  27.  <Button
  28.     android:layout_width="fill_parent"
  29.     android:layout_height="wrap_content"
  30.     android:text="开始下载"
  31.     android:id="@+id/bt"/>
  32. </LinearLayout>


●编写activity文件,


点击(此处)折叠或打开

  1. public class DownLoadActivity extends Activity implements OnClickListener {
  2.     //定义相关控件
  3.     ProgressBar bar;
  4.     Button bt;
  5.     TextView tv ;
  6.     EditText et_text;
  7.     boolean flag = true;
  8.     boolean stopflag = false;
  9.     Handler handler = new Handler(){

  10.         @Override
  11.         public void handleMessage(Message msg) {
  12.             bar.setProgress(total);
  13.             int max = bar.getMax();
  14.             if (total>=(max-1)) {
  15.                 total = max;
  16.                 flag = false;
  17.             }
  18.             int result = total*100/max;
  19.             tv.setText("当前进度:"+result+"%");
  20.             super.handleMessage(msg);
  21.         }
  22.         
  23.     };
  24.     int total = 0;
  25.     @Override
  26.     public void onCreate(Bundle savedInstanceState) {
  27.         super.onCreate(savedInstanceState);
  28.         setContentView(R.layout.main);
  29.         //初始化相关控件
  30.         bar = (ProgressBar) this.findViewById(R.id.bar);
  31.         bt = (Button)this.findViewById(R.id.bt);
  32.         tv = (TextView)this.findViewById(R.id.tv_process);
  33.         et_text=(EditText)this.findViewById(R.id.et_path);
  34.         bt.setOnClickListener(this);
  35.     }
  36.     @Override
  37.     public void onClick(View v) {
  38.         switch (v.getId()) {
  39.         case R.id.bt:
  40.             if ("开始下载".equals(bt.getText().toString().trim())) {
  41.                 bt.setText("暂停");
  42.                 stopflag = false;
  43.             }else {
  44.                 bt.setText("开始下载");
  45.                 stopflag=true;
  46.             }
  47.             new Thread(){

  48.                 @Override
  49.                 public void run() {
  50.                     while (flag) {
  51.                         try {
  52.                             sleep(1000);
  53.                             Message message = new Message();
  54.                             //通知更新UI
  55.                             handler.sendMessage(message);
  56.                         } catch (Exception e) {
  57.                             // TODO: handle exception
  58.                         }
  59.                     }
  60.                     super.run();
  61.                 }
  62.                 
  63.             }.start();
  64.             //得到下载路径
  65.             String path = et_text.getText().toString().trim();
  66.             if ("".equals(path)) {
  67.                 Toast.makeText(this, "路径不能为空", 0).show();
  68.                 return;
  69.             }
  70.             try {
  71.                 URL url = new URL(path);
  72.                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  73.                 //设置请求的相关参数
  74.                 conn.setRequestMethod("GET");
  75.                 conn.setConnectTimeout(5000);
  76.                 conn.setRequestProperty("User-Agent",
  77.                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  78.                 int code = conn.getResponseCode();
  79.                 if (code ==200) {
  80.                     int length = conn.getContentLength();
  81.                     RandomAccessFile file = new RandomAccessFile("/mnt/sdcard/" + getFileName(path), "rwd");
  82.                  //设置文件长度
  83.                     file.setLength(length);
  84.                     //设置进度条最大值
  85.                  bar.setMax(length);
  86.                  //建立3条线程下载数据
  87.                  int threadNO = 3;
  88.                  //每条线程下载数据的大小
  89.                  int blocksize = length/threadNO;
  90.                 
  91.                  for (int i = 0; i <threadNO; i++) {
  92.                         int startposition = i*blocksize;//每条线程下载的开始位置
  93.                         int endposition = (i+1)*blocksize;//每条线程下载的结束位置
  94.                         if (i==(threadNO-1)) {
  95.                             endposition = length;//如果整个文件的大小不为线程个数的整数倍,则最后一个线程的结束位置即为文件的总长度
  96.                         }
  97.                         DownLoadTask task = new DownLoadTask(i,path,startposition,endposition);
  98.                         task.start();
  99.                     }
  100.                 }
  101.             } catch (Exception e) {
  102.                 // TODO: handle exception
  103.                 Toast.makeText(this,"下载出现异常",0).show();
  104.             }
  105.             
  106.             break;
  107.         }
  108.     }
  109.     class DownLoadTask extends Thread{
  110.         int threadid;
  111.         String path;
  112.         int startposition;
  113.         int endposition;
  114.         public DownLoadTask(int threadid, String path, int startposition,
  115.                 int endposition) {
  116.             this.threadid = threadid;
  117.             this.path = path;
  118.             this.startposition = startposition;
  119.             this.endposition = endposition;
  120.         }
  121.         @Override
  122.         public void run() {
  123.             // TODO Auto-generated method stub
  124.             try {
  125.                 //为每个线程创建一个文件用于记录暂停下载时当时已下载的数据大小
  126.                 File postionfile = new File("/mnt/sdcard/" + threadid + ".txt");
  127.                 URL url = new URL(path);
  128.                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  129.                 System.out.println("线程" + threadid + "正在下载 " + "开始位置 : "
  130.                         + startposition + "结束位置 " + endposition);
  131.                 if (postionfile.exists()) {
  132.                     FileInputStream is = new FileInputStream(postionfile);
  133.                     //处理流信息得到以下载的字节数大小
  134.                     byte[] result = StreamTool.getByte(is);
  135.                     String str = new String(result);
  136.                     if (!"".equals(str)) {
  137.                         //如果postionfile中有记录,则改变开始下载的位置
  138.                         int newstartposition = Integer.parseInt(str);
  139.                         if (newstartposition>startposition) {
  140.                             startposition = newstartposition;
  141.                         }
  142.                     }
  143.                 }
  144.                 
  145.                 conn.setRequestProperty("Range", "bytes=" + startposition + "-"
  146.                         + endposition);
  147.                 conn.setRequestMethod("GET");
  148.                 conn.setConnectTimeout(5000);
  149.                 conn.setRequestProperty("User-Agent",
  150.                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  151.                 InputStream is = conn.getInputStream();
  152.                 RandomAccessFile file = new RandomAccessFile("/mnt/sdcard/"
  153.                         + getFileName(path), "rwd");
  154.                 file.seek(startposition);
  155.                 byte[] buffer = new byte[1024];
  156.                 int len = 0;
  157.                 int currentPosition = startposition;
  158.                 while ((len = is.read(buffer))!=-1) {
  159.                     if (stopflag) {
  160.                         return;
  161.                     }
  162.                     file.write(buffer, 0, len);
  163.                     synchronized (DownLoadActivity.this) {
  164.                         total+=len;
  165.                     }
  166.                     //记录当前线程以下载的数据
  167.                     currentPosition+=len;
  168.                     String position = currentPosition+"";
  169.                     FileOutputStream out = new FileOutputStream(postionfile);
  170.                     //把记录写入文件
  171.                     out.write(position.getBytes());
  172.                     out.flush();
  173.                     out.close();
  174.                     
  175.                 }
  176.                 file.close();
  177.                 System.out.println("线程"+threadid+"下载完毕");
  178.                 if (postionfile.exists()) {
  179.                     postionfile.delete();
  180.                 }
  181.             } catch (Exception e) {
  182.             }
  183.             super.run();
  184.         }
  185.     }
  186.     public String getFileName(String path){
  187.         int start = path.lastIndexOf("/")+1;
  188.         return path.substring(start, path.length());
  189.     }
  190. }

  ●最后一个就是一个处理输入流的工具类,返回字节数:


点击(此处)折叠或打开

  1. public class StreamTool {
  2.     public static byte[] getByte(InputStream is) throws Exception{
  3.         ByteArrayOutputStream out = new ByteArrayOutputStream();
  4.         int len = 0;
  5.         byte[] b = new byte[1024];
  6.         while ((len = is.read(b))!=-1) {
  7.             out.write(b, 0, len);
  8.         }
  9.         is.close();
  10.         out.flush();
  11.         return out.toByteArray();
  12.     }
  13. }

运行后看到^0^


暂停后:


阅读(5696) | 评论(0) | 转发(2) |
0

上一篇:Json方式获取网络数据

下一篇:没有了

给主人留下些什么吧!~~