App中有很多通用的功能,如设置模块,有缓存、无图模式、版本更新等一些通用的功能,与大家分享一下其中的版本检查更新,在我们的App中能自动检查更新升级。

首先我们要先获得我们应用当前版本,接着从服务器获得应用的最新版本,两个一比较如果最新版本高于当前版本就同升级更新。


代码实现:

获得当前版本:

public static int getCurrVersion(Context context){

PackageManager pm = context.getPackageManager();

try {

PackageInfo info = pm.getPackageInfo(context

.getPackageName(), 0);

return info.versionCode;

} catch (NameNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return 0;

}

从服务器获得最新版本:

public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{

XmlPullParser parser = Xml.newPullParser();

parser.setInput(is, "utf-8");//设置解析的数据源 7. int type = parser.getEventType();

UpdataInfo info = new UpdataInfo();//实体 9. while(type != XmlPullParser.END_DOCUMENT ){

switch (type) {

case XmlPullParser.START_TAG:

if("version".equals(parser.getName())){

info.setVersion(parser.nextText()); //获取版本号 }else if ("url".equals(parser.getName())){

info.setUrl(parser.nextText()); //获取要升级的APK文件 }else if ("description".equals(parser.getName())){

info.setDescription(parser.nextText()); //获取该文件的信息 18. }

break;

}

type = parser.next();

}

return info;

}

从服务器下载apk:

1.public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{

//如果相等的话表示当前的sdcard挂载在手机上并且是可用的

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

//获取到文件的大小

pd.setMax(conn.getContentLength());

InputStream is = conn.getInputStream();

File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");

FileOutputStream fos = new FileOutputStream(file);

BufferedInputStream bis = new BufferedInputStream(is);

byte[] buffer = new byte[1024];

int len ;

int total=0;

while((len =bis.read(buffer))!=-1){

fos.write(buffer, 0, len);

total+= len;

//获取当前下载量

pd.setProgress(total);

}

. fos.close();

bis.close();

is.close();

return file;

}

else{

. return null;

}

然后进行安装

protected void installApk(File file) {

Intent intent = new Intent();

//执行动作

intent.setAction(Intent.ACTION_VIEW);

//执行的数据类型

intent.setDataAndType(Uri.fromFile(file), "application/vnd.Android.package-archive");//

startActivity(intent);

}