public Context _context = null; //老版本号 public int versionCode = 0; //老版本名 public String versionName = ""; //新版本号 public int newVerCode; //新版本名 public String newVerName;
private ProgressDialog myDialog; private Long fileSize = 1l; private int downLoadFileSize;
private int activity_id;
public Update(Context context, int Id) { _context = context; activity_id = Id; } //获取版本号 public static int getVerCode(Context context) { int verCode = -1; try { verCode = context.getPackageManager().getPackageInfo("com.nc", 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return verCode; } //获取版本名 public static String getVerName(Context context) { String verName = ""; try { verName = context.getPackageManager().getPackageInfo("com.nc", 0).versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } return verName; } //检查是否有更新 public void check(){ if(activity_id == Data.UPDATE_MORE){ myDialog = new ProgressDialog(_context); myDialog.setMessage("正在检测更新"); myDialog.setButton("取消", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { // finish(); } }); myDialog.show(); } getServerVerCode(); } //获取软件名 public static String getApkName(Context context) { String verName = context.getResources().getText(R.string.apk_name).toString(); return verName; } //获取服务器端版本号 private void getServerVerCode() { new Thread(){ public void run() { HTTPRequestHelper httpHelper_ver = new HTTPRequestHelper(verHandler); String targetUrl = Data.WEBROOT + BASEURL_VER; httpHelper_ver.performGet(targetUrl); }; }.start(); }
不客氣
PackageManager packageManager = getPackageManager();
//getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
当前版本的信息 packInfo.versionCdoe; 2.从服务器获取最新版本号,如果>packInfo.versionCdoe提示用户进行升级
也可以在自己的服务器端写一个单独的版本cgi,程序启动的时候去服务器检查这个cgi的版本号。这样的好处是你在告知用户有新版本的时候,可以提供能多新特性之类的信息
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import com.nc.Data;
import com.nc.R;
import com.http.HTTPRequestHelper;/**
* 检查软件更新
* @author saber
*
*/
public class Update {
//服务器中软件文本信息地址
private static final String BASEURL_VER ="mobile/apk_version.txt";
public Context _context = null;
//老版本号
public int versionCode = 0;
//老版本名
public String versionName = "";
//新版本号
public int newVerCode;
//新版本名
public String newVerName;
private ProgressDialog myDialog;
private Long fileSize = 1l;
private int downLoadFileSize;
private int activity_id;
public Update(Context context, int Id) {
_context = context;
activity_id = Id;
}
//获取版本号
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo("com.nc", 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return verCode;
}
//获取版本名
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo("com.nc", 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return verName;
} //检查是否有更新
public void check(){
if(activity_id == Data.UPDATE_MORE){
myDialog = new ProgressDialog(_context);
myDialog.setMessage("正在检测更新");
myDialog.setButton("取消", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) {
// finish();
} });
myDialog.show();
}
getServerVerCode();
}
//获取软件名
public static String getApkName(Context context) {
String verName = context.getResources().getText(R.string.apk_name).toString();
return verName;
}
//获取服务器端版本号
private void getServerVerCode() {
new Thread(){
public void run() {
HTTPRequestHelper httpHelper_ver = new HTTPRequestHelper(verHandler);
String targetUrl = Data.WEBROOT + BASEURL_VER;
httpHelper_ver.performGet(targetUrl);
};
}.start();
}
private Handler verHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
String response = msg.getData().getString("RESPONSE"); try {
JSONArray array = new JSONArray(response);
if (array.length() > 0) {
JSONObject obj = array.getJSONObject(0);
try {
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
} catch (Exception e) {
newVerCode = -1;
newVerName = "";
}
}
}catch(JSONException e) {
e.printStackTrace();
}finally{
if(activity_id == Data.UPDATE_MORE){
myDialog.cancel();
}
}
int vercode = getVerCode(_context); // 用到前面第一节写的方法
if (newVerCode > vercode) {
doNewVersionUpdate(); // 更新新版本
} else {
if(activity_id == Data.UPDATE_MORE){
notNewVersionShow(); // 提示当前为最新版本
}
}
};
};
//不是新版本
private void notNewVersionShow() {
String verName = getVerName(_context);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append("\n" + "已是最新版,无需更新!");
Dialog dialog = new AlertDialog.Builder(_context).setTitle("软件更新")
.setMessage(sb.toString())// 设置内容
.setPositiveButton("确定",// 设置确定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).create();// 创建
// 显示对话框
dialog.show();
} //子函数,若是有新版本,则
private void doNewVersionUpdate() {
String verName = getVerName(_context);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append(", 发现新版本:");
sb.append(newVerName);
sb.append(", 是否更新?");
Dialog dialog = new AlertDialog.Builder(_context)
.setTitle("软件更新")
.setMessage(sb.toString())
// 设置内容
.setPositiveButton("更新",// 设置确定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
myDialog = new ProgressDialog(_context);
myDialog.setCancelable(false);
myDialog.setTitle("正在下载");
myDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downFile(Data.WEBROOT + "mobile/" + getApkName(_context));
}
})
.setNegativeButton("暂不更新",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).create();// 创建
// 显示对话框
dialog.show();
}
//下载软件
private void downFile(final String url) {
myDialog.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
// params[0]代表连接的url
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
fileSize = entity.getContentLength();
//注意如果值超过int范围即报错
myDialog.setMax(fileSize.intValue());
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(Environment.getExternalStorageDirectory(), getApkName(_context));
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
downLoadFileSize += ch;
myDialog.setProgress(downLoadFileSize);
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
myDialog.cancel();
downLoadFileSize = 0;
install();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
//安装软件
private void install() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/" + getApkName(_context))),
"application/vnd.android.package-archive");
_context.startActivity(intent);
}
}