Android 异步下载封装

public class HttpDownFilesRequest extends AsyncTask{

private UserCallBack back;// 传入接口

private String code;// 请求返回码

private String Url;// 请求URL地址;

private Context context;// 上下文

private boolean heard;// 是否加session头

private ProgressDialog dialog;// 对话框

private String seveFilepath;

int count = 0;

static boolean cancelUpgrade = false;

/**

* 请求构造方法

*

* @param context

*            上下文内容

* @param back

*            接口用于得到返回值

* @param code

*            返回标记code

* @param Url

*            请求链接

* @param heard

*            标题头

* @param seveFilepath

*            保存文件路径

*/

public HttpDownFilesRequest(Context context, UserCallBack back,

String seveFilepath, String code, String Url, boolean heard,

boolean IsCompress) {

this.back = back;

this.seveFilepath = seveFilepath;

this.code = code;

this.Url = Url;

this.context = context;

this.heard = heard;

}

@Override

protected String doInBackground(String... arg0) {

String result = "";

if (!NetUtils.checkNetworkInfo(context)) {

result = "网络异常";

return "网络未连接";

}

back.undayway(true);

/*

* 新增 7-26 @sunql

*/

HttpParams httpParameters = new BasicHttpParams();

httpParameters.setParameter(HTTP.UTF_8, HTTP.UTF_8);

// 设置 连接请求超时时间

HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);

// 设置 socket 读取超时时间

HttpConnectionParams.setSoTimeout(httpParameters, 20000);

HttpClient client = new DefaultHttpClient(httpParameters);

// 请求超时

client.getParams().setParameter(

CoreConnectionPNames.CONNECTION_TIMEOUT, Config.httpTimeOut);

HttpGet get = new HttpGet(Url);

HttpResponse response;

InputStream is = null;

FileOutputStream fileOutputStream = null;

try {

response = client.execute(get);

HttpEntity entity = response.getEntity();

final long length = entity.getContentLength();

is = entity.getContent();

fileOutputStream = null;

if (is != null) {

File file = new File(seveFilepath);

fileOutputStream = new FileOutputStream(file);

byte[] buf = new byte[1024];

int ch = -1;

count = 0;

while ((ch = is.read(buf)) != -1) {

fileOutputStream.write(buf, 0, ch);

count += ch;

// 反馈下载进度

publishProgress((int) (count * 100 / length));

if (cancelUpgrade)

break;

}

fileOutputStream.flush();

// 下载完成

if (count == length) {

result = "下载完成";

}

}

result = EntityUtils.toString(response.getEntity());

} catch (ClientProtocolException e) {

result = "下载失败";

} catch (IOException e) {

result = "IO异常";

} catch (Exception e) {

} finally {

if (is != null) {

try {

is.close();

} catch (IOException e) {

Log.e("DownloadThread", e.toString());

result = "IO异常";

}

}

if (fileOutputStream != null) {

try {

fileOutputStream.close();

} catch (IOException e) {

Log.e("DownloadThread", e.toString());

result = "IO异常";

}

}

}

return result;

}

@Override

protected void onPostExecute(String result) {// 在doInBackground执行完成后系统会自动调用,result是返回值

if (dialog != null && dialog.isShowing()) {

dialog.dismiss();

dialog = null;

}

String msg = "";

if (result.equals("下载完成")) {

context.startActivity(getApkFileIntent(seveFilepath));

back.onSuccess(result, code);// 请求成功接口

} else if (result.equals("网络异常")) {

Toast.makeText(context, result, Toast.LENGTH_SHORT).show();

back.onFail(result, code);

} else if (result.trim().equals("IO异常")) {

Toast.makeText(context, result, Toast.LENGTH_SHORT).show();

back.onFail(result, code);// 请求失败接口

} else if (result.equals("下载失败")) {

Toast.makeText(context, result, Toast.LENGTH_SHORT).show();

back.onFail(result, code);// 请求失败接口

}

if (!msg.equals("")) {

Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

}

}

@Override

protected void onPreExecute() {// 执行后台耗时操作前执行

if (!code.equals("下载插件...")) {

dialog = new ProgressDialog(context);

dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

dialog.setMessage("正在下载...");

dialog.setCancelable(false);

dialog.setCanceledOnTouchOutside(false);

dialog.show();

}

}

@Override

protected void onProgressUpdate(Integer... progress) {

for (int i = 0; i < progress.length; i++) {

System.out.println("progress" + i + "=" + progress[i]);

}

if (progress[0] > 0) {

dialog.setMessage("下载中...");

}

dialog.setProgress((int) (progress[0]));

}

// Android获取一个用于打开APK文件的intent

public static Intent getApkFileIntent(String param) {

Intent intent = new Intent();

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.setAction(android.content.Intent.ACTION_VIEW);

Uri uri = Uri.fromFile(new File(param));

intent.setDataAndType(uri, "application/vnd.android.package-archive");

return intent;

}

}

你可能感兴趣的:(Android 异步下载封装)