一史煎、聯(lián)網(wǎng)獲取所需下載文件的長度
/**
* 獲取服務(wù)器文件長度
* @param url 需要下載的文件地址
*/
private Observable<Long> getRemoteFileLength(final String url) {
return Observable.create(new Observable.OnSubscribe<Long>() {
@Override
public void call(Subscriber<? super Long> subscriber) {
Request.Builder builder = new Request.Builder();
builder.addHeader("Accept-Encoding", "identity");
Request request = builder.url(url).build();
try {
Response response = mOkHttpClient.newCall(request).execute();
long l = response.body().contentLength();
updateState.fileLength = l;
subscriber.onNext(l);
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
二畦贸、構(gòu)建緩存文件(遍歷緩存目錄里的文件判斷文件是否可以斷點(diǎn)續(xù)傳)
/**
* 構(gòu)建本地文件
* @param context
* @param rootDir 放置下載的文件的根目錄
* @param fileLength 所需下載文件的總長度
* @return
*/
private Observable<File> buildTargetFile(final Context context, final File rootDir, final long fileLength) {
return Observable.create(new Observable.OnSubscribe<File>() {
@Override
public void call(Subscriber<? super File> subscriber) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager
.getRunningAppProcesses();
File downsDir = new File(rootDir, "downs");
if (!downsDir.exists() || !downsDir.isDirectory()) {
downsDir.mkdirs();
}
File[] files = downsDir.listFiles();
File lastFile = null;
if (files.length > 0) {
for (File itemFile : files) {
boolean willContinueDownload = pickFile2ContinueDownload(itemFile, processInfos, fileLength);
if (willContinueDownload) {
if (lastFile != null && lastFile.length() < itemFile.length()) {
lastFile = itemFile;
} else {
lastFile = itemFile;
}
}
}
}
//把斷點(diǎn)續(xù)傳的文件改名掛載到自己的進(jìn)程下
String downloadFileName = "remote_" + getProcessName(Process.myPid(), context) + "_" + Process.myPid() + "_" + fileLength + "_.apk";
File downloadFile = null;
if (lastFile != null) {
if (lastFile.getName().contains(".part")) {
downloadFileName += ".part";
}
downloadFile = new File(downsDir, downloadFileName);
lastFile.renameTo(downloadFile);
} else {
try {
downloadFileName += ".part";
File file = new File(downsDir, downloadFileName);
//lastFile 為空說明沒有合適的文件斷點(diǎn)續(xù)傳(正在被進(jìn)程使用的文件不應(yīng)該斷點(diǎn)續(xù)傳,容易發(fā)生文件復(fù)寫的bug)
// 構(gòu)建當(dāng)前進(jìn)程名寝杖、進(jìn)程ID和文件長度相關(guān)的文件又存在,說明當(dāng)前正在下載
//這種情況下onNext不應(yīng)該傳file進(jìn)去下載,忽略本次下載行為
if (!file.exists()) {//目標(biāo)文件不存在的情況下,構(gòu)建新的文件,從零開始下載apk
downloadFile = new File(downsDir, downloadFileName);
downloadFile.createNewFile();
}
} catch (IOException e) {
subscriber.onError(e);
e.printStackTrace();
}
}
subscriber.onNext(downloadFile);
}
});
}
判該文件是否可以斷點(diǎn)續(xù)傳的方法
/**
* 判斷文件是否可以斷點(diǎn)續(xù)傳
*
* @param file 需要檢查文件
* @param processInfos 進(jìn)程列表
* @param remoteFileLength 服務(wù)器文件長度(條件允許最好換成MD5值校驗(yàn))
*/
private boolean pickFile2ContinueDownload(File file, List<ActivityManager.RunningAppProcessInfo> processInfos, long remoteFileLength) {
if (!file.exists() || !file.isFile()) {
return false;
}
String name = file.getName();
//長度為5 1.remote 2.進(jìn)程名 3.pid 4.文件長度 5.后綴
String[] items = name.split("_");
//下載以remote_為前綴
if (items.length != 5 || !items[0].equals("remote")) {
return false;
}
//比較文件長度,如果文件長度不一致,那么說明文件不是同一個(gè),不應(yīng)該斷點(diǎn)續(xù)傳
String lengthStr = items[3];
if (Long.valueOf(lengthStr) != remoteFileLength) {
return false;
}
String processName = items[1];
String pid = items[2];
for (ActivityManager.RunningAppProcessInfo item : processInfos) {
//如果進(jìn)程名和pid都一樣,那么說明該文件有可能正在被使用,不應(yīng)該作為斷點(diǎn)續(xù)傳文件(容易發(fā)生文件重復(fù)寫入)
if (item.processName.equals(processName) && Integer.valueOf(pid) == item.pid) {
return false;
}
}
return true;
}
三段多、下載服務(wù)器端文件到上文創(chuàng)建的目標(biāo)文件中
/**
*
* @param url 需要下載的文件地址
* @param targetFile 本地存放文件
* @return
*/
private Observable<File> downloadFile(final String url, final File targetFile) {
return Observable.create(new Observable.OnSubscribe<File>() {
@Override
public void call(Subscriber<? super File> subscriber) {
if (targetFile == null) {
subscriber.onError(new Exception("正在下載"));
return;
}
updateState.currentLength = targetFile.length();
updateState.rangeLength = targetFile.length();
try {
byte[] readBytes = new byte[4096 * 2];
Request.Builder builder = new Request.Builder();
if (targetFile.length() > 0) {
builder.addHeader("Range", "bytes=" + targetFile.length() + "-");
}
builder.addHeader("Accept-Encoding", "identity");
Request request = builder.url(url).build();
Response response = mOkHttpClient.newCall(request).execute();
if (response == null) {
return;
}
InputStream inputStream = response.body().byteStream();
FileOutputStream fos = new FileOutputStream(targetFile.getAbsoluteFile(), true);
while (true) {
int readLength = inputStream.read(readBytes);
if (readLength == -1) {
break;
}
updateState.currentLength += readLength;
fos.write(readBytes, 0, readLength);
}
fos.close();
inputStream.close();
String name = targetFile.getName();
name = name.replace(".part", "");
File file = new File(targetFile.getParentFile(), name);
boolean flag = targetFile.renameTo(file);
if (flag) {
subscriber.onNext(file);
} else {
subscriber.onError(new Exception("下載失敗"));
}
} catch (IOException e) {
subscriber.onError(e);
e.printStackTrace();
}
}
});
}
整體調(diào)用過程如下
/**
* @param context 下載所用到的上下文
* @param rootDir 根目錄
*/
public void download(final String url, final Context context, final File rootDir) {
updateState = new UpdateState();
getRemoteFileLength(url).
flatMap(new Func1<Long, Observable<File>>() {
@Override
public Observable<File> call(Long aLong) {
return buildTargetFile(context, rootDir, aLong);
}
}).flatMap(new Func1<File, Observable<File>>() {
@Override
public Observable<File> call(File file) {
return downloadFile(url, file);
}
}).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.newThread())
.subscribe(new Subscriber<File>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
if (throwable != null) {
throwable.printStackTrace();
}
}
@Override
public void onNext(File file) {
//最后進(jìn)行文件長度校驗(yàn),文件長度和文件名標(biāo)記長度必須一直,如果不一致,則說明下載出錯(cuò),文件被復(fù)寫
String name = file.getName();
//長度為5 1.remote 2.進(jìn)程名 3.pid 4.文件長度 5.后綴
String[] items = name.split("_");
//下載以remote_為前綴
if (items.length != 5 || !items[0].equals("remote")) {
FileUtil.delete(file);
updateState.updateFail = true;
return;
}
String lengthStr = items[3];
LOG.e("記錄文件長度-->" + lengthStr + "--真實(shí)文件長度-->" + file.length());
if (Long.valueOf(lengthStr) != file.length()) {
FileUtil.delete(file);
LOG.e("文件長度不一致,文件被復(fù)寫過");
updateState.updateFail = true;
return;
}
updateState.apkFile = file;
LOG.e("下載完成文件-->" + file.getName() + "--位置-->" + file.getAbsolutePath());
}
});
}
其它
獲取進(jìn)程名的方法
/**
* 獲取進(jìn)程名
*
* @param context 上下文
*/
private String getProcessName(int pID, Context context) {
String processName = null;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo info : runningAppProcesses) {
try {
if (info.pid == pID) {
processName = info.processName;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return processName;
}
保存當(dāng)前文件下載進(jìn)度的類
/**
* 記錄文件下載的狀態(tài)
*/
public static class UpdateState {
public long fileLength;
public long currentLength;
public long rangeLength;
public int progress;
public File apkFile;
public boolean updateFail = false;
public void buildProgressInt() {
progress = (int) ((double) currentLength * 100 / (double) fileLength);
}
}