1. 程式人生 > >從伺服器下載指定檔案的標準方法

從伺服器下載指定檔案的標準方法

FileDownlaodTask.java  :  

package com.amlogic.dvb_util;

import java.io.File;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.request.GetRequest;

import android.util.Log;
import okhttp3.Call;
import okhttp3.Response;

/**
*類名:BackupDowloadTask.java 類說明:
*/
public class FileDownloadTask {

private OnProgressCallback mCallback = null;
private String mUrl, mFilePath, mFileName;
private GetRequest mFileDownloadRequest = null;
private static FileDownloadTask instance = null;

private FileDownloadTask(String downloadSource, String localPath, String fileName, OnProgressCallback callback) {
mCallback = callback;
mUrl = downloadSource;
mFilePath = localPath;
mFileName = fileName;
}

public static FileDownloadTask getInstance(String downloadSource, String localPath, String fileName, OnProgressCallback callback){
if(instance == null){
synchronized (FileDownloadTask.class) {
if(instance == null){
instance = new FileDownloadTask(downloadSource, localPath, fileName, callback);
}
}
}
return instance;
}

public void download(){
if(null == mUrl && "".equals(mUrl)){
mCallback.onError(null, null, new Exception("Illegal url"));
return;
}
if (IS_DEBUG)
Log.d(TAG, "---start download--- " + (null == mFileDownloadRequest));
if (null == mFileDownloadRequest) {
mFileDownloadRequest = OkGo.get(mUrl).tag(mUrl);
mFileDownloadRequest.execute(new DownLoadFileCallback(mFilePath, mFileName));
} else {
mFileDownloadRequest.setCallback(new DownLoadFileCallback(mFilePath, mFileName));
}
}

public void setOnProgressCallback(OnProgressCallback callback) {
this.mCallback = callback;
}

private class DownLoadFileCallback extends FileCallback{

public DownLoadFileCallback(String destFileDir, String destFileName) {
super(destFileDir, destFileName);
}

@Override
public void downloadProgress(long currentSize, long totalSize,
float progress, long networkSpeed) {
if (null != mCallback) {
mCallback.onProgressUpdate(currentSize, totalSize, progress, networkSpeed);
}
if (IS_DEBUG)
Log.d(TAG, "---downloadProgress update::" + progress);
}

@Override
public void onError(Call call, Response response, Exception e) {
if (null != mCallback) {
mCallback.onError(call, response, e);
}
if (IS_DEBUG)
Log.d(TAG, "---onError::download failed!");
mFileDownloadRequest = null;
super.onError(call, response, e);
}

public void onSuccess(final File file, Call call, Response response) {
if (IS_DEBUG) {
Log.d(TAG, "---onSuccess---");
}
if (null != mCallback) {
mCallback.onCompleted(file, call, response);
}
mFileDownloadRequest = null;
}
}

public void stopDownloadTask(){
//Activity銷燬時,取消網路請求
        OkGo.getInstance().cancelTag(mUrl);
}

public void release(){
try {
if((Runtime.getRuntime().exec("rm -r " + mFilePath + "/" +  mFileName + "\n").waitFor()) == 0){
if (IS_DEBUG) 
Log.i(TAG, TAG + "FilePath = " + mFilePath + " Release resources!");
}else{
Log.e(TAG, TAG + "FilePath = " + mFilePath + " Cant delete the download cache!");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, TAG + "FilePath = " + mFilePath + "Cant delete the download cache!");
}
}

public void release(String filePath,String fileName){
try {
if((Runtime.getRuntime().exec("rm -r " + filePath + "/" +  fileName + "\n").waitFor()) == 0){
if (IS_DEBUG) 
Log.i(TAG, TAG + "filePath = " + filePath + " Release resources!");
}else{
Log.e(TAG, TAG + "filePath = " + filePath + " Cant delete the download cache!");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, TAG + "filePath = " + filePath + "Cant delete the download cache!");
}
}

public interface OnProgressCallback {
public void onProgressUpdate(long currentSize, long totalSize, float progress, long networkSpeed);
public void onError(Call call, Response response, Exception e);
public void onCompleted(File file, Call call, Response response);
}

private static final String TAG = FileDownloadTask.class.getSimpleName();
private static final boolean IS_DEBUG = true;

}

用法:

        //檔案下載到了/data/data/當前應用包名/files/下

        public void downloadFile(String fileName) {

        String file_dir = getFilesDir().getAbsolutePath() + File.separator + fileName;

        // 如果檔案存在則先刪除

        File file = new File(file_dir);

        if (file.exists()) {

            file.delete();

        }

final FileDownloadTask downloadTask =         FileDownloadTask.getInstance(URL,
getFilesDir().getAbsolutePath(), fileName, null);

downloadTask.setOnProgressCallback(new OnProgressCallback() {

@Override
public void onProgressUpdate(long currentSize, long totalSize, float progress, long networkSpeed) {

}

@Override

public void onError(Call call, Response response, Exception e) {

                                //下載錯誤了可以給主執行緒發訊息,以便彈出提示框

mUpdateUiHandler.sendEmptyMessage(MSG_UI_DOWNLAOD_FAIL);
}

@Override
public void onCompleted(final File file, Call call, Response response) {

//檔案下載完成,可以給主執行緒發訊息,以便彈出提示框

                                mUpdateUiHandler.sendEmptyMessage(MSG_UI_DOWNLAOD_SUCCESS);

}
});

                downloadTask.download();

         }

    這裡需要3個jar,可到我的下載資源裡去下載。