DBOpenHelper.java
package com.amlapp.update.otaupgrade.download;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper {
// 數據庫文件的文件名
private static final String DBNAME = "download.db";
// 數據庫的版本號
private static final int VERSION = 1;
public DBOpenHelper(Context context) {
super(context, DBNAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS filedownlog");
onCreate(db);
}
}
DownloadThread.java
package com.amlapp.update.otaupgrade.download;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import android.util.Log;
public class DownloadThread extends Thread {
private static final String TAG = "DownloadThread";
/** 本地保存文件 */
private File saveFile;
/** 下載路徑 */
private URL downUrl;
/** 該線程要下載的長度 */
private int block;
/** 線程ID */
private int threadId = -1;
/** 該線程已下載的長度 */
private int downLength;
/** 是不是下載完成 */
private boolean finish = false;
/** 文件下載器 */
private FileDownloader downloader;
/***
* 構造方法
*/
public DownloadThread(FileDownloader downloader, URL downUrl,
File saveFile, int block, int downLength, int threadId) {
this.downUrl = downUrl;
this.saveFile = saveFile;
this.block = block;
this.downloader = downloader;
this.threadId = threadId;
this.downLength = downLength;
}
/**
* 線程主方法
*/
@Override
public void run() {
if (downLength < block) {// 未下載完成
try {
HttpURLConnection http = (HttpURLConnection) downUrl
.openConnection();
http.setConnectTimeout(5 * 1000);
http.setRequestMethod("GET");
http.setRequestProperty(
"Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash,"
+ " application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, "
+ "application/x-ms-application, application/vnd.ms-excel,"
+ " application/vnd.ms-powerpoint, application/msword, */*");
http.setRequestProperty("Accept-Language", "zh-CN");
http.setRequestProperty("Referer", downUrl.toString());
http.setRequestProperty("Charset", "UTF⑻");
// 該線程開始下載位置
int startPos = block * (threadId - 1) + downLength;
// 該線程下載結束位置
int endPos = block * threadId - 1;
// 設置獲得實體數據的范圍
http.setRequestProperty("Range", "bytes=" + startPos + "-"
+ endPos);
http.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0;"
+ " .NET CLR 1.1.4322; .NET CLR 2.0.50727; "
+ ".NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
http.setRequestProperty("Connection", "Keep-Alive");
/****/
System.out.println("DownloadThread http.getResponseCode():"
+ http.getResponseCode());
if (http.getResponseCode() == 206) {
/***
* //獲得輸入流 InputStream inStream = http.getInputStream();
* byte[] buffer = new byte[1024]; int offset = 0;
* print("Thread " + this.threadId +
* " start download from position " + startPos);
*
* // rwd: 打開以便讀取和寫入,對 "rw",還要求對文件內容的每一個更新都同步寫入到基礎存儲裝備。
* //對Android移動裝備1定要注意同步,否則當移動裝備斷電的話會丟失數據 RandomAccessFile
* threadfile = new RandomAccessFile( this.saveFile, "rwd");
* //直接移動到文件開始位置下載的 threadfile.seek(startPos); while
* (!downloader.getExit() && (offset = inStream.read(buffer,
* 0, 1024)) != ⑴) { threadfile.write(buffer, 0,
* offset);//開始寫入數據到文件 downLength += offset; //該線程和下載的長度增加
* downloader.update(this.threadId,
* downLength);//修改數據庫中該線程已下載的數據長度
* downloader.append(offset);//文件下載器已下載的總長度增加 }
* threadfile.close();
*
* print("Thread " + this.threadId + " download finish");
* this.finish = true;
**/
// 獲得輸入流
InputStream inStream = http.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inStream);
byte[] buffer = new byte[1024 * 4];
int offset = 0;
RandomAccessFile threadfile = new RandomAccessFile(
this.saveFile, "rwd");
// 獲得RandomAccessFile的FileChannel
FileChannel outFileChannel = threadfile.getChannel();
// 直接移動到文件開始位置下載的
outFileChannel.position(startPos);
// 分配緩沖區的大小
while (!downloader.getExit()
&& (offset = bis.read(buffer)) != -1) {
outFileChannel
.write(ByteBuffer.wrap(buffer, 0, offset));// 開始寫入數據到文件
downLength += offset; // 該線程和下載的長度增加
downloader.update(this.threadId, downLength);// 修改數據庫中該線程已下載的數據長度
downloader.append(offset);// 文件下載器已下載的總長度增加
}
outFileChannel.close();
threadfile.close();
inStream.close();
print("Thread " + this.threadId + " download finish");
this.finish = true;
}
} catch (Exception e) {
this.downLength = -1;
print("Thread " + this.threadId + ":" + e);
}
}
}
private static void print(String msg) {
Log.i(TAG, msg);
}
/**
* 下載是不是完成
*
* @return
*/
public boolean isFinish() {
return finish;
}
/**
* 已下載的內容大小
*
* @return 如果返回值為⑴,代表下載失敗
*/
public long getDownLength() {
return downLength;
}
}
FileDownloader.java
package com.amlapp.update.otaupgrade.download;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.content.Context;
import android.util.Log;
/**
* 文件下載器
*/
public class FileDownloader {
private static final String TAG = "FileDownloader";
/** 上下文 */
private Context context;
/** 文件下載服務類 */
private FileService fileService;
/** 是不是停止下載 */
private boolean exit;
/** 已下載文件長度 */
private int downloadSize = 0;
/** 原始文件長度 */
private int fileSize = 0;
/** 用于下載的線程數組 */
private DownloadThread[] threads;
/** 本地保存文件 */
private File saveFile;
/** 緩存各線程下載的長度 */
private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();
/** 每條線程下載的長度 */
private int block;
/** 下載路徑 */
private String downloadUrl;
/**
* 構建文件下載器
*
* @param downloadUrl
* 下載路徑
* @param fileSaveDir
* 文件保存目錄
* @param threadNum
* 下載線程數
*/
public FileDownloader(Context context, String downloadUrl,
File fileSaveDir, int threadNum) {
try {
this.context = context;
this.downloadUrl = downloadUrl;
fileService = new FileService(this.context);
// 根據指定的下載路徑,生成URL
URL url = new URL(this.downloadUrl);
if (!fileSaveDir.exists())
fileSaveDir.mkdirs();// 如果保存路徑不存在,則新建1個目錄
// 根據指定的線程數來新建線程數組
this.threads = new DownloadThread[threadNum];
// 打開HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設置 HttpURLConnection的斷開時間
conn.setConnectTimeout(5 * 1000);
// 設置 HttpURLConnection的要求方式
conn.setRequestMethod("GET");
// 設置 HttpURLConnection的接收的文件類型
conn.setRequestProperty(
"Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
+ "application/x-shockwave-flash, application/xaml+xml, "
+ "application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, "
+ "application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
// 設置 HttpURLConnection的接收語音
conn.setRequestProperty("Accept-Language", "zh-CN");
// 指定要求uri的源資源地址
conn.setRequestProperty("Referer", downloadUrl);
// 設置 HttpURLConnection的字符編碼
conn.setRequestProperty("Charset", "UTF⑻");
// 檢查閱讀頁面的訪問者在用甚么操作系統(包括版本號)閱讀器(包括版本號)和用戶個人偏好
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2;"
+ " Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; "
+ ".NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152;"
+ " .NET CLR 3.5.30729)");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
// 打印Http協議頭
printResponseHeader(conn);
// 如果返回的狀態碼為200表示正常
//System.out.println("conn.getResponseCode():"+conn.getResponseCode());
if (conn.getResponseCode() == 200) {
this.fileSize = conn.getContentLength();// 根據響應獲得文件大小
if (this.fileSize <= 0)
throw new RuntimeException("Unkown file size ");
String filename = getFileName(conn);// 獲得文件名稱
this.saveFile = new File(fileSaveDir, filename);// 構建保存文件
Map<Integer, Integer> logdata = fileService
.getData(downloadUrl);// 獲得下載記錄
if (logdata.size() > 0) {// 如果存在下載記錄
for (Map.Entry<Integer, Integer> entry : logdata.entrySet())
data.put(entry.getKey(), entry.getValue());// 把各條線程已下載的數據長度放入data中
}
if (this.data.size() == this.threads.length) {// 下面計算所有線程已下載的數據總長度
for (int i = 0; i < this.threads.length; i++) {
this.downloadSize += this.data.get(i + 1);
}
print("已下載的長度" + this.downloadSize);
}
// 計算每條線程下載的數據長度
this.block = (this.fileSize % this.threads.length) == 0 ? this.fileSize
/ this.threads.length
: this.fileSize / this.threads.length + 1;
} else {
throw new RuntimeException("server no response ");
}
} catch (Exception e) {
print(e.toString());
throw new RuntimeException("don't connection this url");
}
}
/**
* 獲得線程數
*/
public int getThreadSize() {
return threads.length;
}
/**
* 退出下載
*/
public void exit() {
this.exit = true;
}
/**
* 是不是退出下載
*/
public boolean getExit() {
return this.exit;
}
/**
* 獲得文件大小
*/
public int getFileSize() {
return fileSize;
}
/**
* 累計已下載大小
* 該方法在具體某個線程下載的時候會被調用
*/
protected synchronized void append(int size) {
downloadSize += size;
}
/**
* 更新指定線程最后下載的位置
* 該方法在具體某個線程下載的時候會被調用
* @param threadId
* 線程id
* @param pos
* 最后下載的位置
*/
protected synchronized void update(int threadId, int pos) {
// 緩存各線程下載的長度
this.data.put(threadId, pos);
// 更新數據庫中的各線程下載的長度
this.fileService.update(this.downloadUrl, threadId, pos);
}
/**
* 獲得文件名
*
* @param conn
* Http連接
*/
private String getFileName(HttpURLConnection conn) {
String filename = this.downloadUrl.substring(this.downloadUrl
.lastIndexOf('/') + 1);// 截取下載路徑中的文件名
// 如果獲得不到文件名稱
if (filename == null || "".equals(filename.trim())) {
// 通過截取Http協議頭分析下載的文件名
for (int i = 0;; i++) {
String mine = conn.getHeaderField(i);
if (mine == null)
break;
/**
* Content-disposition 是 MIME 協議的擴大,MIME 協議唆使 MIME
* 用戶代理如何顯示附加的文件。
* Content-Disposition就是當用戶想把要求所得的內容存為1個文件的時候提供1個默許的文件名
* 協議頭中的Content-Disposition格式以下:
* Content-Disposition","attachment;filename=FileName.txt");
*/
if ("content-disposition".equals(conn.getHeaderFieldKey(i)
.toLowerCase())) {
// 通過正則表達式匹配出文件名
Matcher m = Pattern.compile(".*filename=(.*)").matcher(
mine.toLowerCase());
// 如果匹配到了文件名
if (m.find())
return m.group(1);// 返回匹配到的文件名
}
}
// 如果還是匹配不到文件名,則默許取1個隨機數文件名
filename = UUID.randomUUID() + ".tmp";
}
return filename;
}
/**
* 開始下載文件
*
* @param listener
* 監聽下載數量的變化,如果不需要了解實時下載的數量,可以設置為null
* @return 已下載文件大小
* @throws Exception
*/
public int download(DownloadProgressListener listener) throws Exception {
try {
RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
if (this.fileSize > 0)
randOut.setLength(this.fileSize);
randOut.close();
URL url = new URL(this.downloadUrl);
// 如果本來未曾下載或本來的下載線程數與現在的線程數不1致
if (this.data.size() != this.threads.length) {
this.data.clear();// 清除原來的線程數組
for (int i = 0; i < this.threads.length; i++) {
this.data.put(i + 1, 0);// 初始化每條線程已下載的數據長度為0
}
this.downloadSize = 0;
}
//循環遍歷線程數組
for (int i = 0; i < this.threads.length; i++) {
int downLength = this.data.get(i + 1); // 獲得當前線程下載的文件長度
// 判斷線程是不是已完成下載,否則繼續下載
if (downLength < this.block
&& this.downloadSize < this.fileSize) {
//啟動線程開始下載
this.threads[i] = new DownloadThread(this, url,
this.saveFile, this.block, this.data.get(i + 1),
i + 1);
this.threads[i].setPriority(7);
this.threads[i].start();
} else {
this.threads[i] = null;
}
}
//如果存在下載記錄,從數據庫中刪除它們
fileService.delete(this.downloadUrl);
//重新保存下載的進度到數據庫
fileService.save(this.downloadUrl, this.data);
boolean notFinish = true;// 下載未完成
while (notFinish) {// 循環判斷所有線程是不是完成下載
Thread.sleep(900);
notFinish = false;// 假定全部線程下載完成
for (int i = 0; i < this.threads.length; i++) {
if (this.threads[i] != null && !this.threads[i].isFinish()) {// 如果發現線程未完成下載
notFinish = true;// 設置標志為下載沒有完成
// 如果下載失敗,再重新下載
if (this.threads[i].getDownLength() == -1) {
this.threads[i] = new DownloadThread(this, url,
this.saveFile, this.block,
this.data.get(i + 1), i + 1);
this.threads[i].setPriority(7);
this.threads[i].start();
}
}
}
if (listener != null)
listener.onDownloadSize(this.downloadSize,this.fileSize);// 通知目前已下載完成的數據長度
}
// 如果下載完成
if (downloadSize == this.fileSize)
fileService.delete(this.downloadUrl);// 下載完成刪除記錄
} catch (Exception e) {
print(e.toString());
throw new Exception("file download error");
}
return this.downloadSize;
}
/**
* 獲得Http響應頭字段
* @param http
* @return
*/
public static Map<String, String> getHttpResponseHeader(
HttpURLConnection http) {
Map<String, String> header = new LinkedHashMap<String, String>();
for (int i = 0;; i++) {
String mine = http.getHeaderField(i);
if (mine == null)
break;
header.put(http.getHeaderFieldKey(i), mine);
}
return header;
}
/**
* 打印Http頭字段
*
* @param http
*/
public static void printResponseHeader(HttpURLConnection http) {
Map<String, String> header = getHttpResponseHeader(http);
for (Map.Entry<String, String> entry : header.entrySet()) {
String key = entry.getKey() != null ? entry.getKey() + ":" : "";
print(key + entry.getValue());
}
}
/**
* 獲得網址內容
* @param url
* @return
* @throws Exception
*/
public static String getContent(String url) throws Exception{
StringBuilder sb = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
//設置網絡超時參數
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF⑻"), 8192);
String line = null;
while ((line = reader.readLine())!= null){
sb.append(line + "\n");
}
reader.close();
}
return sb.toString();
}
/**
* 打印信息
* @param msg 信息
*/
private static void print(String msg) {
Log.i(TAG, msg);
}
/**
* 下載進度監聽接口
*/
public interface DownloadProgressListener {
/**
*下載的進度
*/
public void onDownloadSize(int size,int fileSize);
}
}
FileService.java
package com.amlapp.update.otaupgrade.download;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* 文件下載服務類
*/
public class FileService {
private DBOpenHelper openHelper;
public FileService(Context context) {
openHelper = new DBOpenHelper(context);
}
/**
* 獲得每條線程已下載的文件長度
*
* @param path
* @return
*/
public Map<Integer, Integer> getData(String path) {
SQLiteDatabase db = openHelper.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"select threadid, downlength from filedownlog where downpath=?",
new String[] { path });
Map<Integer, Integer> data = new HashMap<Integer, Integer>();
while (cursor.moveToNext()) {
data.put(cursor.getInt(0), cursor.getInt(1));
}
cursor.close();
db.close();
return data;
}
/**
* 保存每條線程已下載的文件長度
*
* @param path
* @param map
*/
public void save(String path, Map<Integer, Integer> map) {// int threadid,
// int position
SQLiteDatabase db = openHelper.getWritableDatabase();
db.beginTransaction();
try {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
db.execSQL(
"insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",
new Object[] { path, entry.getKey(), entry.getValue() });
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close();
}
/**
* 實時更新每條線程已下載的文件長度
*
* @param path
* @param map
*/
public void update(String path, int threadId, int pos) {
SQLiteDatabase db = openHelper.getWritableDatabase();
db.execSQL(
"update filedownlog set downlength=? where downpath=? and threadid=?",
new Object[] { pos, path, threadId });
db.close();
}
/**
* 當文件下載完成后,刪除對應的下載記錄
*
* @param path
*/
public void delete(String path) {
SQLiteDatabase db = openHelper.getWritableDatabase();
db.execSQL("delete from filedownlog where downpath=?",
new Object[] { path });
db.close();
}
}
測試Activity:
package com.moonlight.projectorforge;
import java.io.File;
import com.amlapp.update.otaupgrade.download.FileDownloader;
import com.amlapp.update.otaupgrade.download.FileDownloader.DownloadProgressListener;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncTask<String, Integer, Integer>() {
private String downloadUrl = "http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=asda&step_word=&pn=1&spn=0&di=145126455210&pi=&rn=1&tn=baiduimagedetail&is=&istype=0&ie=utf⑻&oe=utf⑻&in=&cl=2&lm=⑴&st=undefined&cs=3541143192%2C3632970612&os=3611388031%2C2854364844&simid=3432062895%2C349837288&adpicid=0&ln=1976&fr=&fmq=1467017028245_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fwww.hereinuk.com%2Fwp-content%2Fuploads%2F2014%2F07%2Fasda.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3F4r_z%26e3Bojtxtg_z%26e3Bqq_z%26e3Bv54AzdH3Ff%3F__ktz%3DMzA9OTQaMTUzOA%3D%3D%264t1%3Ddaan8b99m%26t1x%3Dd%26fg%3Dkwknnw0ud19bv989jbm0c8m8dcknkdn0&gsm=0&rpstart=0&rpnum=0";
private File fileSaveDir = new File("/storage/external_storage/sda1/");
private int threadNum = 5;
private int totalSize;
@Override
protected Integer doInBackground(String... params) {
FileDownloader loader = new FileDownloader(MainActivity.this, downloadUrl, fileSaveDir, threadNum);
try {
loader.download(new DownloadProgressListener() {
@Override
public void onDownloadSize(int size, int fileSize) {
totalSize = fileSize;
publishProgress(size);
}
});
} catch (Exception e) {
e.printStackTrace();
return -1;
}
return 0;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//Todo show download progress,percentage:100f*values[0]/totalSize
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if(result ==0){
//Todo download success
}else{
//Todo download failed
}
}
}.execute();
}
}