Android 斷點續傳

lostinai發表於2013-08-25
  1. package com.example.downloaderstopsart;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import android.os.Bundle;  
  9. import android.os.Handler;  
  10. import android.os.Message;  
  11. import android.os.StrictMode;  
  12. import android.app.ListActivity;  
  13. import android.view.View;  
  14. import android.widget.LinearLayout;  
  15. import android.widget.LinearLayout.LayoutParams;  
  16. import android.widget.ProgressBar;  
  17. import android.widget.SimpleAdapter;  
  18. import android.widget.TextView;  
  19. import android.widget.Toast;  
  20.   
  21. public class MainActivity extends ListActivity  {  
  22.   
  23.          // 固定下載的資源路徑,這裡可以設定網路上的地址  
  24.           private static final String URL = "http://10.81.36.193:8080/";  
  25.           // 固定存放下載的音樂的路徑:SD卡目錄下  
  26.           private static final String SD_PATH = "/mnt/sdcard/";  
  27.           // 存放各個下載器  
  28.           private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();  
  29.           // 存放與下載器對應的進度條  
  30.           private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();  
  31.           /**  
  32.            * 利用訊息處理機制適時更新進度條  
  33.            */  
  34.           private Handler mHandler = new Handler() {  
  35.               public void handleMessage(Message msg) {  
  36.                   if (msg.what == 1) {  
  37.                       String url = (String) msg.obj;  
  38.                       int length = msg.arg1;  
  39.                       ProgressBar bar = ProgressBars.get(url);  
  40.                       if (bar != null) {  
  41.                           // 設定進度條按讀取的length長度更新  
  42.                           bar.incrementProgressBy(length);  
  43.                           if (bar.getProgress() == bar.getMax()) {  
  44.                               Toast.makeText(MainActivity.this, "下載完成!", 0).show();  
  45.                               // 下載完成後清除進度條並將map中的資料清空  
  46.                               LinearLayout layout = (LinearLayout) bar.getParent();  
  47.                               layout.removeView(bar);  
  48.                               ProgressBars.remove(url);  
  49.                               downloaders.get(url).delete(url);  
  50.                               downloaders.get(url).reset();  
  51.                               downloaders.remove(url);  
  52.                           }  
  53.                       }  
  54.                   }  
  55.               }  
  56.           };  
  57.           @Override  
  58.           public void onCreate(Bundle savedInstanceState) {  
  59.               super.onCreate(savedInstanceState);  
  60.               setContentView(R.layout.activity_main);  
  61.               showListView();  
  62.               StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());  
  63.               StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());  
  64.           }  
  65.           // 顯示listView,這裡可以隨便新增音樂  
  66.           private void showListView() {  
  67.               List<Map<String, String>> data = new ArrayList<Map<String, String>>();  
  68.               Map<String, String> map = new HashMap<String, String>();  
  69.               map.put("name", "mm.mp3");  
  70.               data.add(map);  
  71.               map = new HashMap<String, String>();  
  72.               map.put("name", "pp.mp3");  
  73.               data.add(map);  
  74.               map = new HashMap<String, String>();  
  75.               map.put("name", "tt.mp3");  
  76.               data.add(map);  
  77.               map = new HashMap<String, String>();  
  78.               map.put("name", "ou.mp3");  
  79.               data.add(map);  
  80.               SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list_item, new String[] { "name" },  
  81.                       new int[] { R.id.tv_resouce_name });  
  82.               setListAdapter(adapter);  
  83.           }  
  84.           /**  
  85.            * 響應開始下載按鈕的點選事件  
  86.            */  
  87.           public void startDownload(View v) {  
  88.               // 得到textView的內容  
  89.               LinearLayout layout = (LinearLayout) v.getParent();  
  90.               String musicName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();  
  91.               String urlstr = URL + musicName;  
  92.               String localfile = SD_PATH + musicName;  
  93.               //設定下載執行緒數為4,這裡是我為了方便隨便固定的  
  94.               int threadcount = 4;  
  95.               // 初始化一個downloader下載器  
  96.               Downloader downloader = downloaders.get(urlstr);  
  97.               if (downloader == null) {  
  98.                   downloader = new Downloader(urlstr, localfile, threadcount, this, mHandler);  
  99.                   downloaders.put(urlstr, downloader);  
  100.               }  
  101.               if (downloader.isdownloading())  
  102.                  return;  
  103.              // 得到下載資訊類的個陣列成集合  
  104.              LoadInfo loadInfo = downloader.getDownloaderInfors();  
  105.              // 顯示進度條  
  106.              showProgress(loadInfo, urlstr, v);  
  107.              // 呼叫方法開始下載  
  108.              downloader.download();  
  109.          }  
  110.       
  111.          /**  
  112.           * 顯示進度條  
  113.           */  
  114.          private void showProgress(LoadInfo loadInfo, String url, View v) {  
  115.              ProgressBar bar = ProgressBars.get(url);  
  116.              if (bar == null) {  
  117.                  bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);  
  118.                  bar.setMax(loadInfo.getFileSize());  
  119.                  bar.setProgress(loadInfo.getComplete());  
  120.                  ProgressBars.put(url, bar);  
  121.                  LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 5);  
  122.                  ((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);  
  123.              }  
  124.          }  
  125.          /**  
  126.           * 響應暫停下載按鈕的點選事件  
  127.           */  
  128.          public void pauseDownload(View v) {  
  129.              LinearLayout layout = (LinearLayout) v.getParent();  
  130.              String musicName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();  
  131.              String urlstr = URL + musicName;  
  132.              downloaders.get(urlstr).pause();  
  133.          }  
  134.      }  

DBHelper:

[html] view plaincopy
  1. package com.example.downloaderstopsart;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. /**  
  8.  * 建立一個資料庫幫助類  
  9.  */  
  10. public class DBHelper extends SQLiteOpenHelper {  
  11.     // download.db-->資料庫名  
  12.     public DBHelper(Context context) {  
  13.         super(context, "download.db", null, 1);  
  14.     }  
  15.   
  16.     /**  
  17.      * 在download.db資料庫下建立一個download_info表儲存下載資訊  
  18.      */  
  19.     @Override  
  20.     public void onCreate(SQLiteDatabase db) {  
  21.         db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "  
  22.                 + "start_pos integer, end_pos integer, compelete_size integer,url char)");  
  23.     }  
  24.   
  25.     @Override  
  26.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  27.   
  28.     }  
  29.   
  30. }  

[html] view plaincopy
  1. DownloadInfo:  
[html] view plaincopy
  1. package com.example.downloaderstopsart;  
  2.   
  3. public class DownloadInfo {  
  4.     private int threadId;// 下載器id  
  5.     private int startPos;// 開始點  
  6.     private int endPos;// 結束點  
  7.     private int compeleteSize;// 完成度  
  8.     private String url;// 下載器網路標識  
  9.   
  10.     public DownloadInfo(int threadId, int startPos, int endPos,  
  11.             int compeleteSize, String url) {  
  12.         this.threadId = threadId;  
  13.         this.startPos = startPos;  
  14.         this.endPos = endPos;  
  15.         this.compeleteSize = compeleteSize;  
  16.         this.url = url;  
  17.     }  
  18.   
  19.     public DownloadInfo() {  
  20.     }  
  21.   
  22.     public String getUrl() {  
  23.         return url;  
  24.     }  
  25.   
  26.     public void setUrl(String url) {  
  27.         this.url = url;  
  28.     }  
  29.   
  30.     public int getThreadId() {  
  31.         return threadId;  
  32.     }  
  33.   
  34.     public void setThreadId(int threadId) {  
  35.         this.threadId = threadId;  
  36.     }  
  37.   
  38.     public int getStartPos() {  
  39.         return startPos;  
  40.     }  
  41.   
  42.     public void setStartPos(int startPos) {  
  43.         this.startPos = startPos;  
  44.     }  
  45.   
  46.     public int getEndPos() {  
  47.         return endPos;  
  48.     }  
  49.   
  50.     public void setEndPos(int endPos) {  
  51.         this.endPos = endPos;  
  52.     }  
  53.   
  54.     public int getCompeleteSize() {  
  55.         return compeleteSize;  
  56.     }  
  57.   
  58.     public void setCompeleteSize(int compeleteSize) {  
  59.         this.compeleteSize = compeleteSize;  
  60.     }  
  61.   
  62.     @Override  
  63.     public String toString() {  
  64.         return "DownloadInfo [threadId=" + threadId + "startPos=" + startPos  
  65.                 + ", endPos=" + endPos + "compeleteSize=" + compeleteSize  
  66.                 + "]";  
  67.     }  
  68. }  

LoadInfo:

[html] view plaincopy
  1. package com.example.downloaderstopsart;  
  2.   
  3. public class LoadInfo {  
  4.     public int fileSize;// 檔案大小  
  5.     private int complete;// 完成度  
  6.     private String urlstring;// 下載器標識  
  7.   
  8.     public LoadInfo(int fileSize, int complete, String urlstring) {  
  9.         this.fileSize = fileSize;  
  10.         this.complete = complete;  
  11.         this.urlstring = urlstring;  
  12.     }  
  13.   
  14.     public LoadInfo() {  
  15.     }  
  16.   
  17.     public int getFileSize() {  
  18.         return fileSize;  
  19.     }  
  20.   
  21.     public void setFileSize(int fileSize) {  
  22.         this.fileSize = fileSize;  
  23.     }  
  24.   
  25.     public int getComplete() {  
  26.         return complete;  
  27.     }  
  28.   
  29.     public void setComplete(int complete) {  
  30.         this.complete = complete;  
  31.     }  
  32.   
  33.     public String getUrlstring() {  
  34.         return urlstring;  
  35.     }  
  36.   
  37.     public void setUrlstring(String urlstring) {  
  38.         this.urlstring = urlstring;  
  39.     }  
  40.   
  41.     @Override  
  42.     public String toString() {  
  43.         return "LoadInfo [fileSize=" + fileSize + "complete=" + complete  
  44.                 + ", urlstring=" + urlstring + "]";  
  45.     }  
  46. }  

Downloader:

[html] view plaincopy
  1. package com.example.downloaderstopsart;  
  2. import java.io.File;  
  3. import java.io.InputStream;  
  4.  import java.io.RandomAccessFile;  
  5.  import java.net.HttpURLConnection;  
  6.  import java.net.URL;  
  7.  import java.util.ArrayList;  
  8.  import java.util.List;  
  9.  import android.content.Context;  
  10.  import android.os.Handler;  
  11.  import android.os.Message;  
  12.  import android.util.Log;  
  13.   
  14.  public class Downloader {  
  15.      private String urlstr;// 下載的地址  
  16.      private String localfile;// 儲存路徑  
  17.      private int threadcount;// 執行緒數  
  18.      private Handler mHandler;// 訊息處理器  
  19.      private Dao dao;// 工具類  
  20.      private int fileSize;// 所要下載的檔案的大小  
  21.      private List<DownloadInfo> infos;// 存放下載資訊類的集合  
  22.      private static final int INIT = 1;//定義三種下載的狀態:初始化狀態,正在下載狀態,暫停狀態  
  23.      private static final int DOWNLOADING = 2;  
  24.      private static final int PAUSE = 3;  
  25.      private int state = INIT;  
  26.   
  27.      public Downloader(String urlstr, String localfile, int threadcount,  
  28.              Context context, Handler mHandler) {  
  29.          this.urlstr = urlstr;  
  30.          this.localfile = localfile;  
  31.          this.threadcount = threadcount;  
  32.          this.mHandler = mHandler;  
  33.          dao = new Dao(context);  
  34.      }  
  35.      /**  
  36.       *判斷是否正在下載  
  37.       */  
  38.      public boolean isdownloading() {  
  39.          return state == DOWNLOADING;  
  40.      }  
  41.      /**  
  42.       * 得到downloader裡的資訊  
  43.       * 首先進行判斷是否是第一次下載,如果是第一次就要進行初始化,並將下載器的資訊儲存到資料庫中  
  44.       * 如果不是第一次下載,那就要從資料庫中讀出之前下載的資訊(起始位置,結束為止,檔案大小等),並將下載資訊返回給下載器  
  45.       */  
  46.      public LoadInfo getDownloaderInfors() {  
  47.          if (isFirst(urlstr)) {  
  48.              Log.v("TAG", "isFirst");  
  49.              init();  
  50.              int range = fileSize / threadcount;  
  51.              infos = new ArrayList<DownloadInfo>();  
  52.              for (int i = 0; i < threadcount - 1; i++) {  
  53.                  DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)* range - 1, 0, urlstr);  
  54.                  infos.add(info);  
  55.              }  
  56.              DownloadInfo info = new DownloadInfo(threadcount - 1,(threadcount - 1) * range, fileSize - 1, 0, urlstr);  
  57.              infos.add(info);  
  58.              //儲存infos中的資料到資料庫  
  59.              dao.saveInfos(infos);  
  60.              //建立一個LoadInfo物件記載下載器的具體資訊  
  61.              LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);  
  62.              return loadInfo;  
  63.          } else {  
  64.              //得到資料庫中已有的urlstr的下載器的具體資訊  
  65.              infos = dao.getInfos(urlstr);  
  66.              Log.v("TAG", "not isFirst size=" + infos.size());  
  67.              int size = 0;  
  68.              int compeleteSize = 0;  
  69.              for (DownloadInfo info : infos) {  
  70.                  compeleteSize += info.getCompeleteSize();  
  71.                  size += info.getEndPos() - info.getStartPos() + 1;  
  72.              }  
  73.              return new LoadInfo(size, compeleteSize, urlstr);  
  74.          }  
  75.      }  
  76.   
  77.      /**  
  78.       * 初始化  
  79.       */  
  80.      private void init() {  
  81.          try {  
  82.              URL url = new URL(urlstr);  
  83.              HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  84.              connection.setConnectTimeout(5000);  
  85.              connection.setRequestMethod("GET");  
  86.              fileSize = connection.getContentLength();  
  87.   
  88.              File file = new File(localfile);  
  89.              if (!file.exists()) {  
  90.                  file.createNewFile();  
  91.              }  
  92.              // 本地訪問檔案  
  93.              RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");  
  94.              accessFile.setLength(fileSize);  
  95.              accessFile.close();  
  96.              connection.disconnect();  
  97.          } catch (Exception e) {  
  98.              e.printStackTrace();  
  99.          }  
  100.      }  
  101.   
  102.      /**  
  103.       * 判斷是否是第一次 下載  
  104.       */  
  105.      private boolean isFirst(String urlstr) {  
  106.          return dao.isHasInfors(urlstr);  
  107.      }  
  108.   
  109.      /**  
  110.       * 利用執行緒開始下載資料  
  111.       */  
  112.      public void download() {  
  113.          if (infos != null) {  
  114.              if (state == DOWNLOADING)  
  115.                  return;  
  116.              state = DOWNLOADING;  
  117.              for (DownloadInfo info : infos) {  
  118.                  new MyThread(info.getThreadId(), info.getStartPos(),  
  119.                          info.getEndPos(), info.getCompeleteSize(),  
  120.                          info.getUrl()).start();  
  121.              }  
  122.          }  
  123.      }  
  124.   
  125.      public class MyThread extends Thread {  
  126.          private int threadId;  
  127.          private int startPos;  
  128.          private int endPos;  
  129.          private int compeleteSize;  
  130.          private String urlstr;  
  131.   
  132.          public MyThread(int threadId, int startPos, int endPos,  
  133.                  int compeleteSize, String urlstr) {  
  134.              this.threadId = threadId;  
  135.              this.startPos = startPos;  
  136.              this.endPos = endPos;  
  137.              this.compeleteSize = compeleteSize;  
  138.              this.urlstr = urlstr;  
  139.          }  
  140.          @Override  
  141.          public void run() {  
  142.              HttpURLConnection connection = null;  
  143.              RandomAccessFile randomAccessFile = null;  
  144.              InputStream is = null;  
  145.              try {  
  146.                   
  147.                  URL url = new URL(urlstr);  
  148.                  connection = (HttpURLConnection) url.openConnection();  
  149.                  connection.setConnectTimeout(5000);  
  150.                  connection.setRequestMethod("GET");  
  151.                  // 設定範圍,格式為Range:bytes x-y;  
  152.                  connection.setRequestProperty("Range", "bytes="+(startPos + compeleteSize) + "-" + endPos);  
  153.   
  154.                  randomAccessFile = new RandomAccessFile(localfile, "rwd");  
  155.                  randomAccessFile.seek(startPos + compeleteSize);  
  156.                  Log.i("RG", "connection--->>>"+connection);  
  157.                  // 將要下載的檔案寫到儲存在儲存路徑下的檔案中  
  158.                  is = connection.getInputStream();  
  159.                  byte[] buffer = new byte[4096];  
  160.                  int length = -1;  
  161.                  while ((length = is.read(buffer)) != -1) {  
  162.                      randomAccessFile.write(buffer, 0, length);  
  163.                      compeleteSize += length;  
  164.                      // 更新資料庫中的下載資訊  
  165.                      dao.updataInfos(threadId, compeleteSize, urlstr);  
  166.                      // 用訊息將下載資訊傳給進度條,對進度條進行更新  
  167.                      Message message = Message.obtain();  
  168.                      message.what = 1;  
  169.                      message.obj = urlstr;  
  170.                      message.arg1 = length;  
  171.                      mHandler.sendMessage(message);  
  172.                      if (state == PAUSE) {  
  173.                          return;  
  174.                      }  
  175.                  }  
  176.              } catch (Exception e) {  
  177.                  e.printStackTrace();  
  178.              } finally {  
  179.                  try {  
  180.                      is.close();  
  181.                      randomAccessFile.close();  
  182.                      connection.disconnect();  
  183.                      dao.closeDb();  
  184.                  } catch (Exception e) {  
  185.                      e.printStackTrace();  
  186.                  }  
  187.              }  
  188.   
  189.          }  
  190.      }  
  191.      //刪除資料庫中urlstr對應的下載器資訊  
  192.      public void delete(String urlstr) {  
  193.          dao.delete(urlstr);  
  194.      }  
  195.      //設定暫停  
  196.      public void pause() {  
  197.          state = PAUSE;  
  198.      }  
  199.      //重置下載狀態  
  200.      public void reset() {  
  201.         state = INIT;  
  202.      }  
  203.  }  

Dao:

[html] view plaincopy
  1. package com.example.downloaderstopsart;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import android.content.Context;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8.   
  9. public class Dao {  
  10.     private DBHelper dbHelper;  
  11.   
  12.     public Dao(Context context) {  
  13.         dbHelper = new DBHelper(context);  
  14.     }  
  15.   
  16.     /**  
  17.      * 檢視資料庫中是否有資料  
  18.      */  
  19.     public boolean isHasInfors(String urlstr) {  
  20.         SQLiteDatabase database = dbHelper.getReadableDatabase();  
  21.         String sql = "select count(*)  from download_info where url=?";  
  22.         Cursor cursor = database.rawQuery(sql, new String[] { urlstr });  
  23.         cursor.moveToFirst();  
  24.         int count = cursor.getInt(0);  
  25.         cursor.close();  
  26.         return count == 0;  
  27.     }  
  28.   
  29.     /**  
  30.      * 36 * 儲存 下載的具體資訊 37  
  31.      */  
  32.     public void saveInfos(List<DownloadInfo> infos) {  
  33.         SQLiteDatabase database = dbHelper.getWritableDatabase();  
  34.         for (DownloadInfo info : infos) {  
  35.             String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url) values (?,?,?,?,?)";  
  36.             Object[] bindArgs = { info.getThreadId(), info.getStartPos(),  
  37.                     info.getEndPos(), info.getCompeleteSize(), info.getUrl() };  
  38.             database.execSQL(sql, bindArgs);  
  39.         }  
  40.     }  
  41.   
  42.     /**  
  43.      * 得到下載具體資訊  
  44.      */  
  45.     public List<DownloadInfo> getInfos(String urlstr) {  
  46.         List<DownloadInfo> list = new ArrayList<DownloadInfo>();  
  47.         SQLiteDatabase database = dbHelper.getReadableDatabase();  
  48.         String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";  
  49.         Cursor cursor = database.rawQuery(sql, new String[] { urlstr });  
  50.         while (cursor.moveToNext()) {  
  51.             DownloadInfo info = new DownloadInfo(cursor.getInt(0),  
  52.                     cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),  
  53.                     cursor.getString(4));  
  54.             list.add(info);  
  55.         }  
  56.         cursor.close();  
  57.         return list;  
  58.     }  
  59.   
  60.     /**  
  61.      * 更新資料庫中的下載資訊  
  62.      */  
  63.     public void updataInfos(int threadId, int compeleteSize, String urlstr) {  
  64.         SQLiteDatabase database = dbHelper.getReadableDatabase();  
  65.         String sql = "update download_info set compelete_size=? where thread_id=? and url=?";  
  66.         Object[] bindArgs = { compeleteSize, threadId, urlstr };  
  67.         database.execSQL(sql, bindArgs);  
  68.     }  
  69.   
  70.     /**  
  71.      * 關閉資料庫  
  72.      */  
  73.     public void closeDb() {  
  74.         dbHelper.close();  
  75.     }  
  76.   
  77.     /**  
  78.      * 下載完成後刪除資料庫中的資料  
  79.      */  
  80.     public void delete(String url) {  
  81.         SQLiteDatabase database = dbHelper.getReadableDatabase();  
  82.         database.delete("download_info", "url=?", new String[] { url });  
  83.         database.close();  
  84.     }  
  85. }  

xml如下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   <LinearLayout xmlns: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/llRoot">  
  7.       <ListView android:id="@android:id/list"  
  8.           android:layout_width="fill_parent"  
  9.           android:layout_height="fill_parent">  
  10.      </ListView>  
  11.  </LinearLayout>  
  12.    

item_list.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <LinearLayout  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_marginBottom="5dip"  
  11.         android:orientation="horizontal" >  
  12.   
  13.         <TextView  
  14.             android:id="@+id/tv_resouce_name"  
  15.             android:layout_width="fill_parent"  
  16.             android:layout_height="wrap_content"  
  17.             android:layout_weight="1" />  
  18.   
  19.         <Button  
  20.             android:id="@+id/btn_start"  
  21.             android:layout_width="fill_parent"  
  22.             android:layout_height="wrap_content"  
  23.             android:layout_weight="1"  
  24.             android:onClick="startDownload"  
  25.             android:text="下載" />  
  26.   
  27.         <Button  
  28.             android:id="@+id/btn_pause"  
  29.             android:layout_width="fill_parent"  
  30.             android:layout_height="wrap_content"  
  31.             android:layout_weight="1"  
  32.             android:onClick="pauseDownload"  
  33.             android:text="暫停" />  
  34.     </LinearLayout>  
  35.   
  36. </LinearLayout>  

記得加許可權:
[html] view plaincopy
  1. <uses-permission android:name="android.permission.INTERNET"/>  
  2.  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

還有在3.0以上的版本記得加上這句話:
[html] view plaincopy
  1. StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());  
  2.           StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());  

效果圖如下:

相關文章