文件下载工具类:
下载资源:点击打开链接
package cn.com.bjhj.utils.finalfileprogress;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import java.io.File;
import cn.com.bjhj.activity.R;
import cn.com.bjhj.activity.base.HHYBaseActivity;
import cn.com.bjhj.utils.HHYFileUtils;
import cn.com.bjhj.utils.L;
/**
* 类介绍(必填):自定义文件下载附带progressbar
* Created by Jiang on 2017/1/6 14:24.
*/
public class FinalDownFile {
private static final java.lang.String TAG = "自定义文件下载";
private HHYBaseActivity mActivity;
private ProgressBar mProgress;
private boolean cancelUpdate;
private AlertDialog mDownloadDialog;
private String strPath;
private String outPath;
private int rateNum;
private DownFileCallBack callBack;
public FinalDownFile(HHYBaseActivity context, String strPath, String outPath,DownFileCallBack callBack) {
this.mActivity = context;
this.strPath = strPath;
this.outPath = outPath;
this.callBack = callBack;
}
public interface DownFileCallBack{
void onSuccess(File file);
void onFailure(String err);
}
public void showDownloadDialog() {
// 构造软件下载对话框
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(R.string.soft_updating);
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mActivity);
View v = inflater.inflate(R.layout.dialog_softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// 取消下载
builder.setNegativeButton(R.string.soft_update_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mDownloadDialog = builder.create();
mDownloadDialog.setCanceledOnTouchOutside(false);
mDownloadDialog.show();
// 下载文件
downloadFile();
}
private void downloadFile() {
FinalHttp finalHttp = new FinalHttp();
//中文转utf-8
strPath = strPath.replace(HHYFileUtils.getFileName(strPath), Uri.encode(HHYFileUtils.getFileName(strPath)));
finalHttp.download(strPath, outPath, new AjaxCallBack<File>() {
@Override
public void onLoading(long count, long current) {
// super.onLoading(count, current);
mProgress.setMax((int) count);
rateNum = (int) current;
handler.sendEmptyMessage(0);
L.d(TAG,"我是下载进度-=="+count+"\n"+current);
}
@Override
public void onSuccess(File file) {
super.onSuccess(file);
L.d(TAG,"下载成功-==");
mDownloadDialog.dismiss();
callBack.onSuccess(file);
}
@Override
public void onFailure(Throwable t, int errorNo, String strMsg) {
super.onFailure(t, errorNo, strMsg);
L.i(TAG,"下载失败-=="+strMsg);
mDownloadDialog.dismiss();
callBack.onFailure(strMsg);
}
});
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(mActivity != null){
mActivity.onProgress(mProgress, rateNum);
}
}
};
}