Android开发多线程断点续传下载器

来源:互联网 发布:b2b系统源码 编辑:程序博客网 时间:2024/04/28 19:21

使用多线程断点续传下载器在下载的时候多个线程并发可以占用服务器端更多资源,从而加快下载速度,在下载过程中记录每个线程已拷贝数据的数量,如果下载中断,比如无信号断线、电量不足等情况下,这就需要使用到断点续传功能,下次启动时从记录位置继续下载,可避免重复部分的下载。这里采用数据库来记录下载的进度。

效果图

      

断点续传

1.断点续传需要在下载过程中记录每条线程的下载进度

2.每次下载开始之前先读取数据库,查询是否有未完成的记录,有就继续下载,没有则创建新记录插入数据库

3.在每次向文件中写入数据之后,在数据库中更新下载进度

4.下载完成之后删除数据库中下载记录

Handler传输数据

这个主要用来记录百分比,每下载一部分数据就通知主线程来记录时间

1.主线程中创建的View只能在主线程中修改,其他线程只能通过和主线程通信,在主线程中改变View数据

2.我们使用Handler可以处理这种需求

   主线程中创建Handler,重写handleMessage()方法

   新线程中使用Handler发送消息,主线程即可收到消息,并且执行handleMessage()方法

动态生成新View

可实现多任务下载

1.创建XML文件,将要生成的View配置好

2.获取系统服务LayoutInflater,用来生成新的View

   LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

3.使用inflate(int resource, ViewGroup root)方法生成新的View

4.调用当前页面中某个容器的addView,将新创建的View添加进来

示例

进度条样式 download.xml

[html] view plaincopyprint?
  1. <?xmlversion="1.0"encoding="utf-8"?> 
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android" 
  4.     android:layout_width="fill_parent" 
  5.     android:layout_height="wrap_content" 
  6.     > 
  7.     <LinearLayout  
  8.         android:orientation="vertical" 
  9.         android:layout_width="fill_parent" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_weight="1" 
  12.         > 
  13.         <!--进度条样式默认为圆形进度条,水平进度条需要配置style属性, 
  14.         ?android:attr/progressBarStyleHorizontal --> 
  15.         <ProgressBar 
  16.             android:layout_width="fill_parent"  
  17.             android:layout_height="20dp" 
  18.             style="?android:attr/progressBarStyleHorizontal" 
  19.             /> 
  20.         <TextView 
  21.             android:layout_width="wrap_content"  
  22.             android:layout_height="wrap_content" 
  23.             android:layout_gravity="center" 
  24.             android:text="0%" 
  25.             /> 
  26.     </LinearLayout> 
  27.     <Button 
  28.         android:layout_width="40dp" 
  29.         android:layout_height="40dp" 
  30.         android:onClick="pause" 
  31.         android:text="||" 
  32.         /> 
  33. </LinearLayout> 

顶部样式 main.xml

[html] view plaincopyprint?
  1. <?xmlversion="1.0"encoding="utf-8"?> 
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:orientation="vertical" 
  4.     android:layout_width="fill_parent" 
  5.     android:layout_height="fill_parent" 
  6.     android:id="@+id/root" 
  7.     > 
  8.     <TextView   
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="请输入下载路径" 
  12.         /> 
  13.     <LinearLayout  
  14.         android:layout_width="fill_parent" 
  15.         android:layout_height="wrap_content" 
  16.         android:layout_marginBottom="30dp" 
  17.         > 
  18.         <EditText 
  19.             android:id="@+id/path" 
  20.             android:layout_width="fill_parent"  
  21.             android:layout_height="wrap_content"  
  22.             android:singleLine="true" 
  23.             android:layout_weight="1" 
  24.             /> 
  25.         <Button 
  26.             android:layout_width="wrap_content"  
  27.             android:layout_height="wrap_content"  
  28.             android:text="下载" 
  29.             android:onClick="download" 
  30.             /> 
  31.     </LinearLayout> 
  32. </LinearLayout> 
  33.   

MainActivity.java

[java] view plaincopyprint?
  1. public class MainActivityextends Activity { 
  2.     private LayoutInflater inflater; 
  3.     private LinearLayout rootLinearLayout; 
  4.     private EditText pathEditText; 
  5.  
  6.     @Override 
  7.     public void onCreate(Bundle savedInstanceState) { 
  8.         super.onCreate(savedInstanceState); 
  9.         setContentView(R.layout.main); 
  10.  
  11.         //动态生成新View,获取系统服务LayoutInflater,用来生成新的View 
  12.         inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 
  13.         rootLinearLayout = (LinearLayout) findViewById(R.id.root); 
  14.         pathEditText = (EditText) findViewById(R.id.path); 
  15.  
  16.         // 窗体创建之后, 查询数据库是否有未完成任务, 如果有, 创建进度条等组件, 继续下载 
  17.         List<String> list = new InfoDao(this).queryUndone(); 
  18.         for (String path : list) 
  19.             createDownload(path); 
  20.     } 
  21.  
  22.     /**
  23.      * 下载按钮
  24.      * @param view
  25.      */ 
  26.     public void download(View view) { 
  27.         String path = "http://192.168.1.199:8080/14_Web/" + pathEditText.getText().toString(); 
  28.         createDownload(path); 
  29.     } 
  30.  
  31.     /**
  32.      * 动态生成新View
  33.      * 初始化表单数据
  34.      * @param path
  35.      */ 
  36.     private void createDownload(String path) { 
  37.         //获取系统服务LayoutInflater,用来生成新的View 
  38.         LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 
  39.         LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.download,null); 
  40.          
  41.         LinearLayout childLinearLayout = (LinearLayout) linearLayout.getChildAt(0); 
  42.         ProgressBar progressBar = (ProgressBar) childLinearLayout.getChildAt(0); 
  43.         TextView textView = (TextView) childLinearLayout.getChildAt(1); 
  44.         Button button = (Button) linearLayout.getChildAt(1); 
  45.  
  46.         try
  47.             button.setOnClickListener(new MyListener(progressBar, textView, path)); 
  48.             //调用当前页面中某个容器的addView,将新创建的View添加进来 
  49.             rootLinearLayout.addView(linearLayout); 
  50.         } catch (Exception e) { 
  51.             e.printStackTrace(); 
  52.         } 
  53.     } 
  54.  
  55.     private finalclass MyListener implements OnClickListener { 
  56.         private ProgressBar progressBar; 
  57.         private TextView textView; 
  58.         private int fileLen; 
  59.         private Downloader downloader; 
  60.         private String name; 
  61.          
  62.         /**
  63.          * 执行下载
  64.          * @param progressBar //进度条
  65.          * @param textView //百分比
  66.          * @param path  //下载文件路径
  67.          */ 
  68.         public MyListener(ProgressBar progressBar, TextView textView, String path) { 
  69.             this.progressBar = progressBar; 
  70.             this.textView = textView; 
  71.             name = path.substring(path.lastIndexOf("/") +1); 
  72.  
  73.             downloader = new Downloader(getApplicationContext(), handler); 
  74.             try
  75.                 downloader.download(path, 3); 
  76.             } catch (Exception e) { 
  77.                 e.printStackTrace(); 
  78.                 Toast.makeText(getApplicationContext(), "下载过程中出现异常", 0).show(); 
  79.                 throw new RuntimeException(e); 
  80.             } 
  81.         } 
  82.          
  83.         //Handler传输数据 
  84.         private Handler handler = new Handler() { 
  85.             @Override 
  86.             public void handleMessage(Message msg) { 
  87.                 switch (msg.what) { 
  88.                     case 0
  89.                         //获取文件的大小 
  90.                         fileLen = msg.getData().getInt("fileLen"); 
  91.                         //设置进度条最大刻度:setMax() 
  92.                         progressBar.setMax(fileLen); 
  93.                         break
  94.                     case 1
  95.                         //获取当前下载的总量 
  96.                         int done = msg.getData().getInt("done"); 
  97.                         //当前进度的百分比 
  98.                         textView.setText(name + "\t" + done *100 / fileLen + "%"); 
  99.                         //进度条设置当前进度:setProgress() 
  100.                         progressBar.setProgress(done); 
  101.                         if (done == fileLen) { 
  102.                             Toast.makeText(getApplicationContext(), name +" 下载完成", 0).show(); 
  103.                             //下载完成后退出进度条 
  104.                             rootLinearLayout.removeView((View) progressBar.getParent().getParent()); 
  105.                         } 
  106.                         break
  107.                 } 
  108.             } 
  109.         }; 
  110.  
  111.         /**
  112.          * 暂停和继续下载
  113.          */ 
  114.         public void onClick(View v) { 
  115.             Button pauseButton = (Button) v; 
  116.             if ("||".equals(pauseButton.getText())) { 
  117.                 downloader.pause(); 
  118.                 pauseButton.setText("▶"); 
  119.             } else
  120.                 downloader.resume(); 
  121.                 pauseButton.setText("||"); 
  122.             } 
  123.         } 
  124.     } 



Downloader.java

[java] view plaincopyprint?
  1. public class Downloader { 
  2.  
  3.     private int done; 
  4.     private InfoDao dao; 
  5.     private int fileLen; 
  6.     private Handler handler; 
  7.     private boolean isPause; 
  8.  
  9.     public Downloader(Context context, Handler handler) { 
  10.         dao = new InfoDao(context); 
  11.         this.handler = handler; 
  12.     } 
  13.     /**
  14.      * 多线程下载
  15.      * @param path 下载路径
  16.      * @param thCount 需要开启多少个线程
  17.      * @throws Exception
  18.      */ 
  19.     public void download(String path,int thCount) throws Exception { 
  20.         URL url = new URL(path); 
  21.         HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
  22.         //设置超时时间 
  23.         conn.setConnectTimeout(3000); 
  24.         if (conn.getResponseCode() ==200) { 
  25.             fileLen = conn.getContentLength(); 
  26.             String name = path.substring(path.lastIndexOf("/") +1); 
  27.             File file = new File(Environment.getExternalStorageDirectory(), name); 
  28.             RandomAccessFile raf = new RandomAccessFile(file,"rws"); 
  29.             raf.setLength(fileLen); 
  30.             raf.close(); 
  31.              
  32.             //Handler发送消息,主线程接收消息,获取数据的长度 
  33.             Message msg = new Message(); 
  34.             msg.what = 0
  35.             msg.getData().putInt("fileLen", fileLen); 
  36.             handler.sendMessage(msg); 
  37.              
  38.             //计算每个线程下载的字节数 
  39.             int partLen = (fileLen + thCount -1) / thCount; 
  40.             for (int i =0; i < thCount; i++) 
  41.                 new DownloadThread(url, file, partLen, i).start(); 
  42.         } else
  43.             throw new IllegalArgumentException("404 path: " + path); 
  44.         } 
  45.     } 
  46.  
  47.     private finalclass DownloadThread extends Thread { 
  48.         private URL url; 
  49.         private File file; 
  50.         private int partLen; 
  51.         private int id; 
  52.  
  53.         public DownloadThread(URL url, File file,int partLen, int id) { 
  54.             this.url = url; 
  55.             this.file = file; 
  56.             this.partLen = partLen; 
  57.             this.id = id; 
  58.         } 
  59.  
  60.         /**
  61.          * 写入操作
  62.          */ 
  63.         public void run() { 
  64.             // 判断上次是否有未完成任务 
  65.             Info info = dao.query(url.toString(), id); 
  66.             if (info != null) { 
  67.                 // 如果有, 读取当前线程已下载量 
  68.                 done += info.getDone(); 
  69.             } else
  70.                 // 如果没有, 则创建一个新记录存入 
  71.                 info = new Info(url.toString(), id,0); 
  72.                 dao.insert(info); 
  73.             } 
  74.  
  75.             int start = id * partLen + info.getDone();// 开始位置 += 已下载量 
  76.             int end = (id + 1) * partLen -1
  77.  
  78.             try
  79.                 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
  80.                 conn.setReadTimeout(3000); 
  81.                 //获取指定位置的数据,Range范围如果超出服务器上数据范围, 会以服务器数据末尾为准 
  82.                 conn.setRequestProperty("Range","bytes=" + start + "-" + end); 
  83.                 RandomAccessFile raf = new RandomAccessFile(file, "rws"); 
  84.                 raf.seek(start); 
  85.                 //开始读写数据 
  86.                 InputStream in = conn.getInputStream(); 
  87.                 byte[] buf =new byte[1024 *10]; 
  88.                 int len; 
  89.                 while ((len = in.read(buf)) != -1) { 
  90.                     if (isPause) { 
  91.                         //使用线程锁锁定该线程 
  92.                         synchronized (dao) { 
  93.                             try
  94.                                 dao.wait(); 
  95.                             } catch (InterruptedException e) { 
  96.                                 e.printStackTrace(); 
  97.                             } 
  98.                         } 
  99.                     } 
  100.                     raf.write(buf, 0, len); 
  101.                     done += len; 
  102.                     info.setDone(info.getDone() + len); 
  103.                     // 记录每个线程已下载的数据量 
  104.                     dao.update(info);  
  105.                     //新线程中用Handler发送消息,主线程接收消息 
  106.                     Message msg = new Message(); 
  107.                     msg.what = 1
  108.                     msg.getData().putInt("done", done); 
  109.                     handler.sendMessage(msg); 
  110.                 } 
  111.                 in.close(); 
  112.                 raf.close(); 
  113.                 // 删除下载记录 
  114.                 dao.deleteAll(info.getPath(), fileLen);  
  115.             } catch (IOException e) { 
  116.                 e.printStackTrace(); 
  117.             } 
  118.         } 
  119.     } 
  120.  
  121.     //暂停下载 
  122.     public void pause() { 
  123.         isPause = true
  124.     } 
  125.     //继续下载 
  126.     public void resume() { 
  127.         isPause = false
  128.         //恢复所有线程 
  129.         synchronized (dao) { 
  130.             dao.notifyAll(); 
  131.         } 
  132.     } 

Dao:

DBOpenHelper:

[java] view plaincopyprint?
  1. public class DBOpenHelperextends SQLiteOpenHelper { 
  2.  
  3.     public DBOpenHelper(Context context) { 
  4.         super(context, "download.db",null, 1); 
  5.     } 
  6.  
  7.     @Override 
  8.     public void onCreate(SQLiteDatabase db) { 
  9.         db.execSQL("CREATE TABLE info(path VARCHAR(1024), thid INTEGER, done INTEGER, PRIMARY KEY(path, thid))"); 
  10.     } 
  11.  
  12.     @Override 
  13.     public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) { 
  14.     } 
  15.  


InfoDao:

[java] view plaincopyprint?

  1. public class InfoDao { 
  2.     private DBOpenHelper helper; 
  3.  
  4.     public InfoDao(Context context) { 
  5.         helper = new DBOpenHelper(context); 
  6.     } 
  7.  
  8.     public void insert(Info info) { 
  9.         SQLiteDatabase db = helper.getWritableDatabase(); 
  10.         db.execSQL("INSERT INTO info(path, thid, done) VALUES(?, ?, ?)",new Object[] { info.getPath(), info.getThid(), info.getDone() }); 
  11.     } 
  12.  
  13.     public void delete(String path,int thid) { 
  14.         SQLiteDatabase db = helper.getWritableDatabase(); 
  15.         db.execSQL("DELETE FROM info WHERE path=? AND thid=?",new Object[] { path, thid }); 
  16.     } 
  17.  
  18.     public void update(Info info) { 
  19.         SQLiteDatabase db = helper.getWritableDatabase(); 
  20.         db.execSQL("UPDATE info SET done=? WHERE path=? AND thid=?",new Object[] { info.getDone(), info.getPath(), info.getThid() }); 
  21.     } 
  22.  
  23.     public Info query(String path,int thid) { 
  24.         SQLiteDatabase db = helper.getWritableDatabase(); 
  25.         Cursor c = db.rawQuery("SELECT path, thid, done FROM info WHERE path=? AND thid=?",new String[] { path, String.valueOf(thid) }); 
  26.         Info info = null
  27.         if (c.moveToNext()) 
  28.             info = new Info(c.getString(0), c.getInt(1), c.getInt(2)); 
  29.         c.close(); 
  30.  
  31.         return info; 
  32.     } 
  33.  
  34.     public void deleteAll(String path,int len) { 
  35.         SQLiteDatabase db = helper.getWritableDatabase(); 
  36.         Cursor c = db.rawQuery("SELECT SUM(done) FROM info WHERE path=?",new String[] { path }); 
  37.         if (c.moveToNext()) { 
  38.             int result = c.getInt(0); 
  39.             if (result == len) 
  40.                 db.execSQL("DELETE FROM info WHERE path=? ",new Object[] { path }); 
  41.         } 
  42.     } 
  43.  
  44.     public List<String> queryUndone() { 
  45.         SQLiteDatabase db = helper.getWritableDatabase(); 
  46.         Cursor c = db.rawQuery("SELECT DISTINCT path FROM info",null); 
  47.         List<String> pathList = new ArrayList<String>(); 
  48.         while (c.moveToNext()) 
  49.             pathList.add(c.getString(0)); 
  50.         c.close(); 
  51.         return pathList; 
  52.     } 
  53.  

 

转载:http://blog.csdn.net/furongkang/article/details/6838521#comments