package com.jiuqi.njt.ui;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import com.jiuqi.njt.R;
import com.jiuqi.njt.data.OptsharepreInterface;
import com.jiuqi.njt.model.NxwAppVo;
import com.jiuqi.njt.util.Constants;
import com.jiuqi.njt.util.ReturnObject;
import com.jiuqi.njt.util.UIUtil;
/**
* <p>
* 下载APK的任务类
* </p>
*
* <p>
* Copyright: 版权所有 (c)<br>
* Company: 久其
* </p>
*
* @author liyue
* @version 2013-8-9
*/
public class DownLoadApkTask extends AsyncTask<NxwAppVo, Integer, ReturnObject> {
private Context context;
public DownLoadApkTask(Context context) {
this.context = context;
}
private NotificationManager mNotifManager;
private Notification notification;
private RemoteViews views;
@Override
protected void onPreExecute() {
mNotifManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification();
notification.icon = android.R.drawable.stat_sys_download;
// notification.icon=android.R.drawable.stat_sys_download_done;
notification.tickerText = "更新";
notification.when = System.currentTimeMillis();
notification.defaults = Notification.DEFAULT_LIGHTS;
views = new RemoteViews(context.getPackageName(),
R.layout.alert_dialog_progress);
notification.contentView = views;
mNotifManager.notify(100000, notification);
}
@Override
protected void onProgressUpdate(Integer... values) {
views.setProgressBar(R.id.progress, 100, values[0], false);
views.setTextViewText(R.id.progress_percent,"已下载"+download_precent+"%");
views.setTextViewText(R.id.progress_number, totalLength*download_precent/100/1024/1024+"/"+ totalLength/1024/1024+"M");
notification.contentView = views;
mNotifManager.notify(100000, notification);
}
private int download_precent = 0;
private long totalLength;
@Override
protected ReturnObject doInBackground(NxwAppVo... params) {
ReturnObject ro = new ReturnObject();
NxwAppVo vo = params[0];
String url = vo.getUrl();
String fileName = vo.getFileName();
File sdPath = Environment.getExternalStorageDirectory();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bos = null;
InputStream is = null;
try {
// clean apk if exist
File file = new File(sdPath, fileName);
if (file.exists()) {
file.delete();
}
response = client.execute(get);
HttpEntity entity = response.getEntity();
totalLength = entity.getContentLength();
// Log.v(Constants.TAG, "文件大小:" + length/1024/1024 + "M");
is = entity.getContent();
if (is != null) {
fileOutputStream = new FileOutputStream(file);
bos = new BufferedOutputStream(fileOutputStream);
byte[] buf = new byte[1024];
int len = -1;
int progress = 0;
int precent = 0;
while ((len = is.read(buf)) != -1) {
if (isCancelled()) {
ro.isSuccess = false;
return ro;
} else {
bos.write(buf, 0, len);
progress += len;
precent = (int) (((double) progress / totalLength) * 100);
if (totalLength > 0) {
if (precent - download_precent >= 5) {
download_precent = precent;
publishProgress(precent);
}
}
}
}
}
bos.flush();
fileOutputStream.flush();
} catch (ClientProtocolException e) {
ro.isSuccess = false;
e.printStackTrace();
return ro;
} catch (IOException e) {
ro.isSuccess = false;
e.printStackTrace();
return ro;
} finally {
try {
if (is != null) {
is.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ro.isSuccess = true;
ro.data = vo;
ro.name = sdPath.getPath();
return ro;
}
@Override
protected void onPostExecute(ReturnObject result) {
if (result.isSuccess) {
mNotifManager.cancel(100000);
NxwAppVo vo = (NxwAppVo) result.data;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(result.name + "/"
+ vo.getFileName())),
"application/vnd.android.package-archive");
Bundle bundle = new Bundle();
bundle.putString("name", new OptsharepreInterface(context).getPres("account"));
bundle.putString("pwd", new OptsharepreInterface(context).getPres("password"));
intent.putExtras(bundle);
context.startActivity(intent);
// activity.finish();
}
}
public boolean downloadFile(String downloadUrl, File saveFilePath) {
int fileSize = -1;
int downFileSize = 0;
boolean result = false;
int progress = 0;
try {
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (null == conn) {
return false;
}
// 读取超时时间 毫秒级
conn.setReadTimeout(10000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
fileSize = conn.getContentLength();
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(saveFilePath);
byte[] buffer = new byte[1024];
int i = 0;
int tempProgress = -1;
while ((i = is.read(buffer)) != -1) {
downFileSize = downFileSize + i;
// 下载进度
progress = (int) (downFileSize * 100.0 / fileSize);
fos.write(buffer, 0, i);
synchronized (this) {
if (downFileSize == fileSize) {
// 下载完成
mNotifManager.cancel(100000);
} else if (tempProgress != progress) {
// 下载进度发生改变,则发送Message
publishProgress(progress);
tempProgress = progress;
}
}
}
fos.flush();
fos.close();
is.close();
result = true;
} else {
result = false;
}
} catch (Exception e) {
result = false;
}
return result;
}
}