Android斷點續傳

                            斷點續傳

1. 原理:新建數據庫幫助類dbhelper

  public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, "download.db", null, 1);

    }
    /**
     * 數據庫下載表download_info
     * 開始節點,結束節點,文件的總大小,訪問的網址
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        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) {
        // TODO Auto-generated method stub

    }

}
  1. 數據庫中的數據所對應的實體類DownloadInfo
package com.example.test006.entity;

public class DownloadInfo {

    private int threadId;// 下載器id
    private int startPos;// 開始點
    private int endPos;// 結束點
    private int compeleteSize;// 完成度
    private String url;// 下載器網絡標識



    public DownloadInfo(int threadId, int startPos, int endPos,
            int compeleteSize, String url) {
        super();
        this.threadId = threadId;
        this.startPos = startPos;
        this.endPos = endPos;
        this.compeleteSize = compeleteSize;
        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;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
         public String toString() {
             return "DownloadInfo [threadId=" + threadId
                     + ", startPos=" + startPos + ", endPos=" + endPos
                     + ", compeleteSize=" + compeleteSize +"]";
     }
}
  1. 由於是多線程下載,需要新建一個實體類,代表總的下載進度。
 package com.example.test006.entity;

public class LoadInfo {

    public int fileSize;// 文件大小
    private int complete;// 完成度
    private String urlstring;// 下載器標識
    public LoadInfo() {
        super();
        // TODO Auto-generated constructor stub
    }
    public LoadInfo(int fileSize, int complete, String urlstring) {
        super();
        this.fileSize = fileSize;
        this.complete = complete;
        this.urlstring = urlstring;
    }
    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 + "]";
     }
}

4.dao層,與數據庫直接交互

/**
  *
  * 一個業務類
  */
 public class Dao {
     private DBHelper dbHelper;

     public Dao(Context context) {
         dbHelper = new DBHelper(context);

     }

     /**
      * 查看數據庫中是否有數據
      */
     public boolean isHasInfors(String urlstr) {
         SQLiteDatabase database = dbHelper.getReadableDatabase();
        String sql = "select count(*)  from download_info where url=?";
         Cursor cursor = database.rawQuery(sql, new String[] { urlstr });
         cursor.moveToFirst();
         int count = cursor.getInt(0);
        cursor.close();
         return count == 0;
     }

     /**
      * 保存 下載的具體信息
      */
     public void saveInfos(List<DownloadInfo> infos) {
         SQLiteDatabase database = dbHelper.getWritableDatabase();
         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);
         }
     }

     /**
      * 得到下載具體信息
      */
     public List<DownloadInfo> getInfos(String urlstr) {
         List<DownloadInfo> list = new ArrayList<DownloadInfo>();
         SQLiteDatabase database = dbHelper.getReadableDatabase();
         String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";
         Cursor 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);
         }
         cursor.close();
         return list;
     }

     /**
     * 更新數據庫中的下載信息
      */
     public void updataInfos(int threadId, int compeleteSize, String urlstr) {
         SQLiteDatabase database = dbHelper.getReadableDatabase();
         String sql = "update download_info set compelete_size=? where thread_id=? and url=?";
         Object[] bindArgs = { compeleteSize, threadId, urlstr };
        database.execSQL(sql, bindArgs);
     }
     /**
      * 關閉數據庫
      */
     public void closeDb() {
         dbHelper.close();
    }

     /**
     * 下載完成後刪除數據庫中的數據
      */
     public void delete(String url) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
         database.delete("download_info", "url=?", new String[] { url });
         database.close();
     }
 }
  1. dao層與activity層 之間的幫助層。
public class DownLoader {
    private String urlstr;// 下載的地址
    private String localfile;// 保存路徑
    private int threadcount;// 線程數
    private Handler mHandler;// 消息處理器
    private Dao dao;// 工具類
    private int fileSize;// 所要下載的文件的大小
    private List<DownloadInfo> infos;// 存放下載信息類的集合
    private static final int INIT = 1;// 定義三種下載的狀態:初始化狀態,正在下載狀態,暫停狀態
    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;
        dao = new Dao(context);
    }

    /**
     * 判斷是否正在下載
     */
    public boolean isdownloading() {
        return state == DOWNLOADING;
    }

    /**
     * 得到downloader裏的信息 首先進行判斷是否是第一次下載,如果是第一次就要進行初始化,並將下載器的信息保存到數據庫中
     * 如果不是第一次下載,那就要從數據庫中讀出之前下載的信息(起始位置,結束爲止,文件大小等),並將下載信息返回給下載器
     */
    public LoadInfo getDownloaderInfors() {
        if (isFirst(urlstr)) {
            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中的數據到數據庫
            dao.saveInfos(infos);
            // 創建一個LoadInfo對象記載下載器的具體信息
            LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);
            return loadInfo;
        } else {
            // 得到數據庫中已有的urlstr的下載器的具體信息
            infos = dao.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.isHasInfors(urlstr);
    }

    /**
     * 114 * 利用線程開始下載數據 115
     */
    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");
                // 設置範圍,格式爲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;
                    // 更新數據庫中的下載信息
                    dao.updataInfos(threadId, compeleteSize, urlstr);
                    // 用消息將下載信息傳給進度條,對進度條進行更新
                    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();
            } finally {
                try {
                    is.close();
                    randomAccessFile.close();
                    connection.disconnect();
                    dao.closeDb();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 刪除數據庫中urlstr對應的下載器信息
    public void delete(String urlstr) {
        dao.delete(urlstr);
    }

    // 設置暫停
    public void pause() {
        state = PAUSE;
    }

    // 重置下載狀態
    public void reset() {
        state = INIT;
    }
}
  1. activity中的實現
public class MainActivity extends ListActivity {
    // 固定下載的資源路徑,這裏可以設置網絡上的地址
    private static final String URL = "http://10.0.3.2:8080/TomcatTest/xiangce/";
    // 固定存放下載的音樂的路徑:SD卡目錄下
    private static final String SD_PATH = "/mnt/sdcard/";
    // 存放各個下載器
    private Map<String, DownLoader> downloaders = new HashMap<String, DownLoader>();
    // 存放與下載器對應的進度條
    private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();
    /**
     * 31 * 利用消息處理機制適時更新進度條 32
     */
    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) {
                    // 設置進度條按讀取的length長度更新
                    bar.incrementProgressBy(length);
                    if (bar.getProgress() == bar.getMax()) {
                        Toast.makeText(MainActivity.this, "下載完成!", 0).show();
                        // 下載完成後清除進度條並將map中的數據清空
                        LinearLayout layout = (LinearLayout) bar.getParent();
                        layout.removeView(bar);
                        ProgressBars.remove(url);
                        downloaders.get(url).delete(url);
                        downloaders.get(url).reset();
                        downloaders.remove(url);
                    }
                }
            }
        }
    };

    @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", "pic1.jpg");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "pic2.jpg");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "pic3.jpg");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "pic4.jpg");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "pic5.jpg");
        data.add(map);
        SimpleAdapter adapter = new SimpleAdapter(this, data,
                R.layout.list_item, new String[] { "name" },
                new int[] { R.id.tv_resouce_name });
        setListAdapter(adapter);
    }

    /**
     * 83 * 響應開始下載按鈕的點擊事件 84
     */
    public void startDownload(View v) {
        // 得到textView的內容
        LinearLayout layout = (LinearLayout) v.getParent();
        String musicName = ((TextView) layout
                .findViewById(R.id.tv_resouce_name)).getText().toString();
        String urlstr = URL + musicName;
        String localfile = SD_PATH + musicName;
        // 設置下載線程數爲4,這裏是我爲了方便隨便固定的
        int threadcount = 4;
        // 初始化一個downloader下載器
        DownLoader downloader = downloaders.get(urlstr);
        if (downloader == null) {
            downloader = new DownLoader(urlstr, localfile, threadcount, this,
                    mHandler);
            downloaders.put(urlstr, downloader);
        }
        //如果正在下載,不再往下執行。
        if (downloader.isdownloading())
            return;
        // 得到下載信息類的個數組成集合
        LoadInfo loadInfo = downloader.getDownloaderInfors();
        // 顯示進度條
        showProgress(loadInfo, urlstr, v);
        // 調用方法開始下載
        downloader.download();
    }

    /**
     * 顯示進度條
     */
    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());
            System.out.println(loadInfo.getFileSize()+"--"+loadInfo.getComplete());
            ProgressBars.put(url, bar);
            LinearLayout.LayoutParams params = new LayoutParams(
                    LayoutParams.FILL_PARENT, 5);
            ((LinearLayout) ((LinearLayout) v.getParent()).getParent())
                    .addView(bar, params);
        }
    }

    /**
     * 響應暫停下載按鈕的點擊事件
     */
    public void pauseDownload(View v) {
        LinearLayout layout = (LinearLayout) v.getParent();
        String musicName = ((TextView) layout
                .findViewById(R.id.tv_resouce_name)).getText().toString();
        String urlstr = URL + musicName;
        downloaders.get(urlstr).pause();
    }
}
發佈了44 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章