android 多線程斷點(diǎn)續(xù)傳下載 三

文章出處

什么是多線程下載修然?

? 多線程下載其實(shí)就是迅雷,BT一些下載原理,通過多個(gè)線程同時(shí)和服務(wù)器連接,那么你就可以榨取到較高的帶寬了,大致做法是將文件切割成N塊,每塊交給單獨(dú)一個(gè)線程去下載,各自下載完成后將文件塊組合成一個(gè)文件,程序上要完成做切割和組裝的小算法

什么是斷點(diǎn)續(xù)傳?

? 原理和實(shí)現(xiàn)手段,可參考我以前的一篇總結(jié)http://blog.csdn.net/shimiso/article/details/5956314 里面詳細(xì)講解http協(xié)議斷點(diǎn)續(xù)傳的原理,務(wù)必要看懂,否則你無法真正理解本節(jié)代碼

怎么完成多線程斷點(diǎn)續(xù)傳?

? 將兩者合二為一需要程序記住每個(gè)文件塊的下載進(jìn)度,并保存入庫,當(dāng)下載程序啟動(dòng)時(shí)候你需要判斷程序是否已經(jīng)下載過該文件,并取出各個(gè)文件塊的保存記錄,換算出下載進(jìn)度繼續(xù)下載,在這里你需要掌握java多線程的基本知識(shí),handler的使用,以及集合,算法,文件操作等基本技能,同時(shí)還要解決sqlite數(shù)據(jù)庫的同步問題,因?yàn)樗遣惶趺粗С侄嗑€程操作的,控制不好經(jīng)常會(huì)出現(xiàn)庫被鎖定的異常,同時(shí)在android2.3以后就不能activity中直接操作http,否則你將收到系統(tǒng)送上的NetworkOnMainThreadException異常,在UI體驗(yàn)上一定記住要使用異步完成,既然大致思路已經(jīng)清楚,下面我們開始分析程序:

SQLiteOpenHelper類

package cn.demo.DBHelper;  
   
 import android.content.Context;  
import android.database.sqlite.SQLiteDatabase;  
import android.database.sqlite.SQLiteOpenHelper;  
   
     /** 
      * 建立一個(gè)數(shù)據(jù)庫幫助類 
      */  
 public class DBHelper extends SQLiteOpenHelper {  
     //download.db-->數(shù)據(jù)庫名  
     public DBHelper(Context context) {  
         super(context, "download.db", null, 1);  
     }  
       
     /** 
      * 在download.db數(shù)據(jù)庫下創(chuàng)建一個(gè)download_info表存儲(chǔ)下載信息 
      */  
     @Override  
     public void onCreate(SQLiteDatabase db) {  
         db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "  
                 + "start_pos integer, end_pos integer, compelete_size integer,url char)");  
     }  
     @Override  
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
     } 
 } 

數(shù)據(jù)庫操作要借助單例和同步,來保證線程的執(zhí)行順序,以免多個(gè)線程爭相搶用sqlite資源導(dǎo)致異常出現(xiàn)

Dao

package cn.demo.Dao;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import android.content.Context;  
import android.database.Cursor;  
import android.database.sqlite.SQLiteDatabase;  
import cn.demo.DBHelper.DBHelper;  
import cn.demo.entity.DownloadInfo;  
  
/** 
 *  
 * 一個(gè)業(yè)務(wù)類 
 */  
public class Dao {    
    private static Dao dao=null;  
    private Context context;   
    private  Dao(Context context) {   
        this.context=context;  
    }  
    public static  Dao getInstance(Context context){  
        if(dao==null){  
            dao=new Dao(context);   
        }  
        return dao;  
    }  
    public  SQLiteDatabase getConnection() {  
        SQLiteDatabase sqliteDatabase = null;  
        try {   
            sqliteDatabase= new DBHelper(context).getReadableDatabase();  
        } catch (Exception e) {    
        }  
        return sqliteDatabase;  
    }  
  
    /** 
     * 查看數(shù)據(jù)庫中是否有數(shù)據(jù) 
     */  
    public synchronized boolean isHasInfors(String urlstr) {  
        SQLiteDatabase database = getConnection();  
        int count = -1;  
        Cursor cursor = null;  
        try {  
            String sql = "select count(*)  from download_info where url=?";  
            cursor = database.rawQuery(sql, new String[] { urlstr });  
            if (cursor.moveToFirst()) {  
                count = cursor.getInt(0);  
            }   
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != database) {  
                database.close();  
            }  
            if (null != cursor) {  
                cursor.close();  
            }  
        }  
        return count == 0;  
    }  
  
    /** 
     * 保存 下載的具體信息 
     */  
    public synchronized void saveInfos(List<DownloadInfo> infos) {  
        SQLiteDatabase database = getConnection();  
        try {  
            for (DownloadInfo info : infos) {  
                String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url) values (?,?,?,?,?)";  
                Object[] bindArgs = { info.getThreadId(), info.getStartPos(),  
                        info.getEndPos(), info.getCompeleteSize(),  
                        info.getUrl() };  
                database.execSQL(sql, bindArgs);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != database) {  
                database.close();  
            }  
        }  
    }  
  
    /** 
     * 得到下載具體信息 
     */  
    public synchronized List<DownloadInfo> getInfos(String urlstr) {  
        List<DownloadInfo> list = new ArrayList<DownloadInfo>();  
        SQLiteDatabase database = getConnection();  
        Cursor cursor = null;  
        try {  
            String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";  
            cursor = database.rawQuery(sql, new String[] { urlstr });  
            while (cursor.moveToNext()) {  
                DownloadInfo info = new DownloadInfo(cursor.getInt(0),  
                        cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),  
                        cursor.getString(4));  
                list.add(info);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != database) {  
                database.close();  
            }  
            if (null != cursor) {  
                cursor.close();  
            }  
        }  
        return list;  
    }  
  
    /** 
     * 更新數(shù)據(jù)庫中的下載信息 
     */  
    public synchronized void updataInfos(int threadId, int compeleteSize, String urlstr) {  
        SQLiteDatabase database = getConnection();  
        try {  
            String sql = "update download_info set compelete_size=? where thread_id=? and url=?";  
            Object[] bindArgs = { compeleteSize, threadId, urlstr };  
            database.execSQL(sql, bindArgs);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != database) {  
                database.close();  
            }  
        }  
    }  
  
    /** 
     * 下載完成后刪除數(shù)據(jù)庫中的數(shù)據(jù) 
     */  
    public synchronized void delete(String url) {  
        SQLiteDatabase database = getConnection();  
        try {  
            database.delete("download_info", "url=?", new String[] { url });  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != database) {  
                database.close();  
            }  
        }  
    }  
}  

DownLoadAdapter

package cn.demo.download;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;




public class DownLoadAdapter extends BaseAdapter{
     
    private LayoutInflater mInflater;
    private List<Map<String, String>> data;
    private Context context;
    private OnClickListener click;
    
    public DownLoadAdapter(Context context,List<Map<String, String>> data) {
        this.context=context;
        mInflater = LayoutInflater.from(context);
        this.data=data;
    }
    public void refresh(List<Map<String, String>> data) {
        this.data=data;
        this.notifyDataSetChanged();
    }
    public void setOnclick(OnClickListener click) {
         this.click=click;
    }
    
    
    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Map<String, String> bean=data.get(position);
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder(); 
            holder.resouceName=(TextView) convertView.findViewById(R.id.tv_resouce_name);
            holder.startDownload=(Button) convertView.findViewById(R.id.btn_start);
            holder.pauseDownload=(Button) convertView.findViewById(R.id.btn_pause);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        } 
        holder.resouceName.setText(bean.get("name")); 
        return convertView;
    }
    public OnClickListener getClick() {
        return click;
    }
    public void setClick(OnClickListener click) {
        this.click = click;
    }
    private class ViewHolder { 
        public TextView resouceName;
        public Button startDownload;
        public Button pauseDownload;
    }
}

注意子線程不要影響主UI線程,靈活運(yùn)用task和handler,各取所長,保證用戶體驗(yàn),handler通常在主線程中有利于專門負(fù)責(zé)處理UI的一些工作

MainActivity

package cn.demo.download;
 
 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar; 
import android.widget.TextView;
import android.widget.Toast;
import cn.demo.entity.LoadInfo;
import cn.demo.service.Downloader;

 public class MainActivity extends ListActivity { 
     // 固定下載的資源路徑,這里可以設(shè)置網(wǎng)絡(luò)上的地址
     private static final String URL = "http://download.haozip.com/";
     // 固定存放下載的音樂的路徑:SD卡目錄下
     private static final String SD_PATH = "/mnt/sdcard/";
     // 存放各個(gè)下載器
     private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
     // 存放與下載器對應(yīng)的進(jìn)度條
     private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();
     /**
      * 利用消息處理機(jī)制適時(shí)更新進(jìn)度條
      */
     private Handler mHandler = new Handler() {
         public void handleMessage(Message msg) {
             if (msg.what == 1) {
                 String url = (String) msg.obj;
                 int length = msg.arg1;
                 ProgressBar bar = ProgressBars.get(url);
                 if (bar != null) {
                     // 設(shè)置進(jìn)度條按讀取的length長度更新
                     bar.incrementProgressBy(length);
                     if (bar.getProgress() == bar.getMax()) {
                         LinearLayout layout = (LinearLayout) bar.getParent();
                         TextView resouceName=(TextView)layout.findViewById(R.id.tv_resouce_name);
                         Toast.makeText(MainActivity.this, "["+resouceName.getText()+"]下載完成质况!", Toast.LENGTH_SHORT).show();
                         // 下載完成后清除進(jìn)度條并將map中的數(shù)據(jù)清空
                         layout.removeView(bar);
                         ProgressBars.remove(url);
                         downloaders.get(url).delete(url);
                         downloaders.get(url).reset();
                         downloaders.remove(url);
                         
                         Button btn_start=(Button)layout.findViewById(R.id.btn_start);
                         Button btn_pause=(Button)layout.findViewById(R.id.btn_pause);
                         btn_pause.setVisibility(View.GONE);
                         btn_start.setVisibility(View.GONE);
                     }
                 }
             }
         }
     };
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main); 
         showListView();
     }
     // 顯示listView愕宋,這里可以隨便添加
     private void showListView() {
         List<Map<String, String>> data = new ArrayList<Map<String, String>>();
         Map<String, String> map = new HashMap<String, String>();
         map.put("name", "haozip_v3.1.exe");
         data.add(map);
         map = new HashMap<String, String>();
         map.put("name", "haozip_v3.1_hj.exe");
         data.add(map);
         map = new HashMap<String, String>();
         map.put("name", "haozip_v2.8_x64_tiny.exe");
         data.add(map);
         map = new HashMap<String, String>();
         map.put("name", "haozip_v2.8_tiny.exe");
         data.add(map);
         DownLoadAdapter adapter=new DownLoadAdapter(this,data);  
         setListAdapter(adapter);
         
     }
     /**
      * 響應(yīng)開始下載按鈕的點(diǎn)擊事件
      */
     public void startDownload(View v) {
         // 得到textView的內(nèi)容 
         LinearLayout layout = (LinearLayout) v.getParent();
         String resouceName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
         String urlstr = URL + resouceName;
         String localfile = SD_PATH + resouceName;
         //設(shè)置下載線程數(shù)為4,這里是我為了方便隨便固定的
         String threadcount = "4";
         DownloadTask downloadTask=new DownloadTask(v);
         downloadTask.execute(urlstr,localfile,threadcount);
       
     };
    class DownloadTask extends AsyncTask<String, Integer, LoadInfo>{
        Downloader downloader=null; 
        View v=null;
        String urlstr=null;
        public DownloadTask(final View v){
            this.v=v;
        }  
        @Override
        protected void onPreExecute() { 
            Button btn_start=(Button)((View)v.getParent()).findViewById(R.id.btn_start);
            Button btn_pause=(Button)((View)v.getParent()).findViewById(R.id.btn_pause);
            btn_start.setVisibility(View.GONE);
            btn_pause.setVisibility(View.VISIBLE);
        }
        @Override
        protected LoadInfo doInBackground(String... params) {
            urlstr=params[0];
            String localfile=params[1];
            int threadcount=Integer.parseInt(params[2]);
             // 初始化一個(gè)downloader下載器
             downloader = downloaders.get(urlstr);
             if (downloader == null) {
                 downloader = new Downloader(urlstr, localfile, threadcount, MainActivity.this, mHandler);
                 downloaders.put(urlstr, downloader);
             }
             if (downloader.isdownloading())
                 return null;
             // 得到下載信息類的個(gè)數(shù)組成集合
             return downloader.getDownloaderInfors(); 
        }
        @Override
        protected void onPostExecute(LoadInfo loadInfo) {
            if(loadInfo!=null){
                 // 顯示進(jìn)度條
                 showProgress(loadInfo, urlstr, v);
                 // 調(diào)用方法開始下載
                 downloader.download();
            } 
        }
         
     };
     /**
      * 顯示進(jìn)度條
      */
     private void showProgress(LoadInfo loadInfo, String url, View v) {
         ProgressBar bar = ProgressBars.get(url);
         if (bar == null) {
             bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
             bar.setMax(loadInfo.getFileSize());
             bar.setProgress(loadInfo.getComplete());
             ProgressBars.put(url, bar);
             LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 5);
             ((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);
         }
     }
     /**
      * 響應(yīng)暫停下載按鈕的點(diǎn)擊事件
      */
     public void pauseDownload(View v) {
         LinearLayout layout = (LinearLayout) v.getParent();
         String resouceName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
         String urlstr = URL + resouceName;
         downloaders.get(urlstr).pause();
         Button btn_start=(Button)((View)v.getParent()).findViewById(R.id.btn_start);
         Button btn_pause=(Button)((View)v.getParent()).findViewById(R.id.btn_pause);
         btn_pause.setVisibility(View.GONE);
         btn_start.setVisibility(View.VISIBLE);
     }
 }

這是一個(gè)信息的實(shí)體,記錄了一些字典信息,可以認(rèn)為是一個(gè)簡單bean對象

package cn.demo.entity;
 /**
  *創(chuàng)建一個(gè)下載信息的實(shí)體類
  */
 public class DownloadInfo {
     private int threadId;//下載器id
     private int startPos;//開始點(diǎn)
     private int endPos;//結(jié)束點(diǎn)
     private int compeleteSize;//完成度
     private String url;//下載器網(wǎng)絡(luò)標(biāo)識(shí)
     public DownloadInfo(int threadId, int startPos, int endPos,
             int compeleteSize,String url) {
         this.threadId = threadId;
         this.startPos = startPos;
         this.endPos = endPos;
         this.compeleteSize = compeleteSize;
         this.url=url;
     }
     public DownloadInfo() {
     }
     public String getUrl() {
         return url;
     }
     public void setUrl(String url) {
         this.url = url;
     }
     public int getThreadId() {
         return threadId;
     }
     public void setThreadId(int threadId) {
         this.threadId = threadId;
     }
     public int getStartPos() {
         return startPos;
     }
     public void setStartPos(int startPos) {
         this.startPos = startPos;
     }
     public int getEndPos() {
         return endPos;
     }
     public void setEndPos(int endPos) {
         this.endPos = endPos;
     }
     public int getCompeleteSize() {
         return compeleteSize;
     }
     public void setCompeleteSize(int compeleteSize) {
         this.compeleteSize = compeleteSize;
     }
 
     @Override
     public String toString() {
         return "DownloadInfo [threadId=" + threadId
                 + ", startPos=" + startPos + ", endPos=" + endPos
                 + ", compeleteSize=" + compeleteSize +"]";
     }
 }

LoadInfo

package cn.demo.entity;
 /**
  *自定義的一個(gè)記載下載器詳細(xì)信息的類 
  */
 public class LoadInfo {
     public int fileSize;//文件大小
     private int complete;//完成度
     private String urlstring;//下載器標(biāo)識(shí)
     public LoadInfo(int fileSize, int complete, String urlstring) {
         this.fileSize = fileSize;
         this.complete = complete;
         this.urlstring = urlstring;
     }
     public LoadInfo() {
     }
     public int getFileSize() {
         return fileSize;
     }
     public void setFileSize(int fileSize) {
         this.fileSize = fileSize;
     }
     public int getComplete() {
         return complete;
     }
     public void setComplete(int complete) {
         this.complete = complete;
     }
     public String getUrlstring() {
         return urlstring;
     }
     public void setUrlstring(String urlstring) {
         this.urlstring = urlstring;
     }
     @Override
     public String toString() {
         return "LoadInfo [fileSize=" + fileSize + ", complete=" + complete
                 + ", urlstring=" + urlstring + "]";
     }
 }

這是一個(gè)核心類,專門用來處理下載的

package cn.demo.service;
 
 import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.demo.Dao.Dao;
import cn.demo.entity.DownloadInfo;
import cn.demo.entity.LoadInfo;
 
 public class Downloader {
     private String urlstr;// 下載的地址
     private String localfile;// 保存路徑
     private int threadcount;// 線程數(shù)
     private Handler mHandler;// 消息處理器 
     private int fileSize;// 所要下載的文件的大小
     private Context context; 
     private List<DownloadInfo> infos;// 存放下載信息類的集合
     private static final int INIT = 1;//定義三種下載的狀態(tài):初始化狀態(tài)结榄,正在下載狀態(tài)中贝,暫停狀態(tài)
     private static final int DOWNLOADING = 2;
     private static final int PAUSE = 3;
     private int state = INIT;
 
     public Downloader(String urlstr, String localfile, int threadcount,
             Context context, Handler mHandler) {
         this.urlstr = urlstr;
         this.localfile = localfile;
         this.threadcount = threadcount;
         this.mHandler = mHandler;
         this.context = context;
     }
     /**
      *判斷是否正在下載 
      */
     public boolean isdownloading() {
         return state == DOWNLOADING;
     }
     /**
      * 得到downloader里的信息
      * 首先進(jìn)行判斷是否是第一次下載,如果是第一次就要進(jìn)行初始化臼朗,并將下載器的信息保存到數(shù)據(jù)庫中
      * 如果不是第一次下載邻寿,那就要從數(shù)據(jù)庫中讀出之前下載的信息(起始位置,結(jié)束為止视哑,文件大小等)绣否,并將下載信息返回給下載器
      */
     public LoadInfo getDownloaderInfors() {
         if (isFirst(urlstr)) {
             Log.v("TAG", "isFirst");
             init();
             int range = fileSize / threadcount;
             infos = new ArrayList<DownloadInfo>();
             for (int i = 0; i < threadcount - 1; i++) {
                 DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)* range - 1, 0, urlstr);
                 infos.add(info);
             }
             DownloadInfo info = new DownloadInfo(threadcount - 1,(threadcount - 1) * range, fileSize - 1, 0, urlstr);
             infos.add(info);
             //保存infos中的數(shù)據(jù)到數(shù)據(jù)庫
             Dao.getInstance(context).saveInfos(infos);
             //創(chuàng)建一個(gè)LoadInfo對象記載下載器的具體信息
             LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);
             return loadInfo;
         } else {
             //得到數(shù)據(jù)庫中已有的urlstr的下載器的具體信息
             infos = Dao.getInstance(context).getInfos(urlstr);
             Log.v("TAG", "not isFirst size=" + infos.size());
             int size = 0;
             int compeleteSize = 0;
             for (DownloadInfo info : infos) {
                 compeleteSize += info.getCompeleteSize();
                 size += info.getEndPos() - info.getStartPos() + 1;
             }
             return new LoadInfo(size, compeleteSize, urlstr);
         }
     }
 
     /**
      * 初始化
      */
     private void init() {
         try {
             URL url = new URL(urlstr);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setConnectTimeout(5000);
             connection.setRequestMethod("GET");
             fileSize = connection.getContentLength();
 
             File file = new File(localfile);
             if (!file.exists()) {
                 file.createNewFile();
             }
             // 本地訪問文件
             RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
             accessFile.setLength(fileSize);
             accessFile.close();
             connection.disconnect();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }  
     /**
      * 判斷是否是第一次 下載
      */
     private boolean isFirst(String urlstr) {
         return Dao.getInstance(context).isHasInfors(urlstr);
     }
 
     /**
      * 利用線程開始下載數(shù)據(jù)
      */
     public void download() {
         if (infos != null) {
             if (state == DOWNLOADING)
                 return;
             state = DOWNLOADING;
             for (DownloadInfo info : infos) {
                 new MyThread(info.getThreadId(), info.getStartPos(),
                         info.getEndPos(), info.getCompeleteSize(),
                         info.getUrl()).start();
             }
         }
     }
 
     public class MyThread extends Thread {
         private int threadId;
         private int startPos;
         private int endPos;
         private int compeleteSize;
         private String urlstr;
 
         public MyThread(int threadId, int startPos, int endPos,
                 int compeleteSize, String urlstr) {
             this.threadId = threadId;
             this.startPos = startPos;
             this.endPos = endPos;
             this.compeleteSize = compeleteSize;
             this.urlstr = urlstr;
         }
         @Override
         public void run() {
             HttpURLConnection connection = null;
             RandomAccessFile randomAccessFile = null;
             InputStream is = null;
             try {
                 URL url = new URL(urlstr);
                 connection = (HttpURLConnection) url.openConnection();
                 connection.setConnectTimeout(5000);
                 connection.setRequestMethod("GET");
                 // 設(shè)置范圍,格式為Range:bytes x-y;
                 connection.setRequestProperty("Range", "bytes="+(startPos + compeleteSize) + "-" + endPos);
 
                 randomAccessFile = new RandomAccessFile(localfile, "rwd");
                 randomAccessFile.seek(startPos + compeleteSize);
                 // 將要下載的文件寫到保存在保存路徑下的文件中
                 is = connection.getInputStream();
                 byte[] buffer = new byte[4096];
                 int length = -1;
                 while ((length = is.read(buffer)) != -1) {
                     randomAccessFile.write(buffer, 0, length);
                     compeleteSize += length;
                     // 更新數(shù)據(jù)庫中的下載信息
                     Dao.getInstance(context).updataInfos(threadId, compeleteSize, urlstr);
                     // 用消息將下載信息傳給進(jìn)度條挡毅,對進(jìn)度條進(jìn)行更新
                     Message message = Message.obtain();
                     message.what = 1;
                     message.obj = urlstr;
                     message.arg1 = length;
                     mHandler.sendMessage(message);
                     if (state == PAUSE) {
                         return;
                     }
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             }  
         }
     }
     //刪除數(shù)據(jù)庫中urlstr對應(yīng)的下載器信息
     public void delete(String urlstr) {
         Dao.getInstance(context).delete(urlstr);
     }
     //設(shè)置暫停
     public void pause() {
         state = PAUSE;
     }
     //重置下載狀態(tài)
     public void reset() {
         state = INIT;
     }
 }

以下是些xml文件

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
     <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dip">
         <TextView 
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:id="@+id/tv_resouce_name"/>
         <Button
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:text="下載"
             android:id="@+id/btn_start"
             android:onClick="startDownload"/>
         <Button
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:text="暫停"
             android:visibility="gone"
             android:id="@+id/btn_pause"
             android:onClick="pauseDownload"/>
       </LinearLayout>
 </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/llRoot">
     <ListView android:id="@android:id/list"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
     </ListView>
 </LinearLayout>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.demo.download"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">
        <activity
                android:name=".MainActivity" 
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" /> 
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    </application>
</manifest>

運(yùn)行效果如下


源碼下載地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末窒朋,一起剝皮案震驚了整個(gè)濱河市桶略,隨后出現(xiàn)的幾起案子烈拒,更是在濱河造成了極大的恐慌,老刑警劉巖取逾,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異薇溃,居然都是意外死亡菌赖,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進(jìn)店門沐序,熙熙樓的掌柜王于貴愁眉苦臉地迎上來琉用,“玉大人,你說我怎么就攤上這事策幼∫厥保” “怎么了?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵特姐,是天一觀的道長晶丘。 經(jīng)常有香客問我,道長唐含,這世上最難降的妖魔是什么浅浮? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮捷枯,結(jié)果婚禮上滚秩,老公的妹妹穿的比我還像新娘。我一直安慰自己淮捆,他們只是感情好郁油,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著攀痊,像睡著了一般桐腌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上苟径,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天案站,我揣著相機(jī)與錄音,去河邊找鬼棘街。 笑死蟆盐,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蹬碧。 我是一名探鬼主播舱禽,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼炒刁,長吁一口氣:“原來是場噩夢啊……” “哼恩沽!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起翔始,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤罗心,失蹤者是張志新(化名)和其女友劉穎里伯,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體渤闷,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡疾瓮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了飒箭。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片狼电。...
    茶點(diǎn)故事閱讀 38,059評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖弦蹂,靈堂內(nèi)的尸體忽然破棺而出肩碟,到底是詐尸還是另有隱情,我是刑警寧澤凸椿,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布削祈,位于F島的核電站,受9級特大地震影響脑漫,放射性物質(zhì)發(fā)生泄漏髓抑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一优幸、第九天 我趴在偏房一處隱蔽的房頂上張望吨拍。 院中可真熱鬧,春花似錦劈伴、人聲如沸密末。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽严里。三九已至,卻和暖如春追城,著一層夾襖步出監(jiān)牢的瞬間刹碾,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工座柱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留迷帜,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓色洞,卻偏偏與公主長得像戏锹,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子火诸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容