package com.astgo.gocall;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.json.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
/**
* 自动更新管理类
*
* @author yx_yicw
* @date 2013-05-28
*
*/
publicclass UpdateManager {
/**
* 下载中
*/
privatestaticfinalintDOWNLOAD = 1;
/**
* 下载结束
*/
privatestaticfinalintDOWNLOAD_FINISH = 2;
/**
* 远程获取版本信息的url
*/
privatestaticfinal String VERSONINFO_PATH = AstgogooApp.VERSION_DNS+"/test/index.php?route=service/version/queryVersion&client=android&custom=kicall";
/**
* 版本信息hashMap
*/
private HashMap<String, String> versionMap;
/**
* 下载保存路径
*/
private String mSavePath;
/**
* 记录进度条数量
*/
privateintprogress;
/**
* 是否取消更新
*/
privatebooleancancelUpdate = false;
/**
* 更新进度条
*/
private ProgressBar mProgress;
/**
* 下载对话框
*/
private Dialog mDownloadDialog;
private Context mContext;
private Handler mHandler = new Handler() {
publicvoid handleMessage(Message msg) {
switch (msg.what) {
// 正在下载
caseDOWNLOAD:
// 设置进度条位置
mProgress.setProgress(progress);
break;
caseDOWNLOAD_FINISH:
// 安装文件
installApk();
break;
default:
break;
}
};
};
public UpdateManager(Context context) {
this.mContext = context;
}
/**
* 检查版本如果有新版本,弹出更新提示框
*
* @param paramAstgogooApp
*/
publicvoid checkUpdate() {
AstgogooApp astgogoo = (AstgogooApp) mContext
.getApplicationContext();
AsyncHttpClient localAsyncHttpClient = new AsyncHttpClient();
// 设置是否wap网络,因为http请求时wap网络要特殊处理,要设置中国移动代理
localAsyncHttpClient.set_network_wap(astgogoo.network_wap() ? 1 : 0);
localAsyncHttpClient.get(VERSONINFO_PATH,
new AsyncHttpResponseHandler() {
publicvoid onFailure(Throwable throwable,
String responseStr) {
Log.d("gogo", "checkVersion failure" + responseStr);
Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_LONG)
.show();
}
publicvoid onSuccess(String responseStr) {
Log.d("gogo", "jsons6==" + responseStr);
// 获取当前软件版本
int versionCode = getVersionCode(mContext);
if (responseStr != null && !"".equals(responseStr)) {
// 解析版本信息json字符串,初始化版本信息hashMap
setVersionMap(responseStr);
if (versionMap != null && !versionMap.isEmpty()) {
int serviceCode = Integer.valueOf(versionMap
.get("version"));
// 版本判断
if (serviceCode > versionCode) {
// 显示提示对话框
showNoticeDialog();
}
}
}
}
});
}
/**
* 获取软件版本号
*
* @param context
* @return
*/
privateint getVersionCode(Context context) {
int versionCode = 0;
try {
// 获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = context.getPackageManager().getPackageInfo(
"com.astgo.gocall", 0).versionCode;
Log.d("gogo", "current versioncode="+versionCode);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
/**
* 解析版本信息json字符串,初始化版本信息hashMap
*
* @param jsonStr
*/
privatevoid setVersionMap(String jsonStr) {
versionMap = new HashMap<String, String>();
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
versionMap.put("url", jsonObj.getString("updateurl"));
versionMap.put("name", jsonObj.getString("name"));
versionMap.put("version", jsonObj.getString("version"));
versionMap.put("updatenote", jsonObj.getString("updatenote"));
versionMap.put("publishdate", jsonObj.getString("publishdate"));
} catch (Exception e) {
versionMap = null;
e.printStackTrace();
}
}
/**
* 检查SD卡是否有读写权限,如果有显示软件更新对话框
*/
privatevoid showNoticeDialog() {
// 构造对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("软件更新");
builder.setMessage("检测到新版本,立即更新吗");
// 更新
builder.setPositiveButton("更新", new OnClickListener() {
@Override
publicvoid onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 检查存储卡是否有读写权限
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(mContext, "存储卡没有读写权限,下载失败,请插入SD卡",
Toast.LENGTH_LONG).show();
} else {
// 显示下载对话框
showDownloadDialog();
}
}
});
// 稍后更新
builder.setNegativeButton("稍后更新", new OnClickListener() {
@Override
publicvoid onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
/**
* 显示软件下载对话框
*/
privatevoid showDownloadDialog() {
// 构造软件下载对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("正在更新");
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// 取消更新
builder.setNegativeButton("取消", new OnClickListener() {
@Override
publicvoid onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 下载apk文件
downloadApk();
}
/**
* 下载apk文件
*/
privatevoid downloadApk() {
// 启动新线程下载软件
new downloadApkThread().start();
}
/**
* 下载文件线程
*
* @author yx_yicw
*
*/
privateclass downloadApkThread extends Thread {
@Override
publicvoid run() {
try {
// 获得存储卡的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
Log.d("system", "下载文件保存路径为==========" + mSavePath);
URL url = new URL(versionMap.get("url"));
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.connect();
// 获取文件大小
int length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, versionMap.get("name"));
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = newbyte[1024];
// 写入到文件中
do {
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0) {
// 下载完成
Log.d("system", "xiazaiwancheng");
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 取消下载对话框显示
mDownloadDialog.dismiss();
}
};
/**
* 提示SD卡不存在,自动更新失败
*/
privatevoid showNoExitstsSDCard() {
Toast.makeText(mContext, "手机内存没有读写权限,下载失败,请插入SD卡", Toast.LENGTH_LONG).show();
}
/**
* 安装APK文件
*/
privatevoid installApk() {
File apkfile = new File(mSavePath, versionMap.get("name"));
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
"application/vnd.android.package-archive");
mContext.startActivity(i);
}
}
在网上找了个自动更新代码,适当做了改进,改进了Http请求适应wap,请求,增加了没SD卡是,内存卡无读写权限的提示。