下面介绍版本更新
版本更新当然少不了服务器端的支持
首先是服务器端的版本更新的检测文件是xml格式的,放在服务器端的D盘
update.xml
<?xml version="1.0" encoding="utf-8"?>
<info>
<version>1.0</version>
<url>http://mobile.shenhuagroup.com.cn:80/webServer/updateversion</url>
<description>神华移动工单版本更新</description>
</info>
version是要更新的版本号,用于和手机端的版本号作对比
url是新的版本的下载地址
description是和之前版本比较更新的内容
我的服务器端使用springMVC搭建的,下面两个方法分别对应读取update.xml和返回新的版本的apk
//返回新的版本
@RequestMapping(value="/updateversion")
@ResponseBody
public void updateversion (HttpServletRequest request,HttpServletResponse response) throws Exception {
File file = new File("D://sh_mobile.apk");
long fileLength = file.length();
response.setHeader("Content-Length", String.valueOf(fileLength));
if(file.exists()){
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
OutputStream toClient = response.getOutputStream();
toClient.write(buffer);
toClient.flush();
toClient.close();
}
}
//读取检测文件
@RequestMapping(value="/updateversionfile")
@ResponseBody
public void updateversionfile (HttpServletRequest request,HttpServletResponse response) throws Exception {
File file = new File("D://update.xml");
if(file.exists()){
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
OutputStream toClient = response.getOutputStream();
toClient.write(buffer);
toClient.flush();
toClient.close();
}
}
下面介绍客户端的代码
首先是UpdataInfo.java实体类,对应解析的是服务器端的update.xml文档
所以这个更新程序不能放在service里面了
因为这个android程序需要联网从服务器下载更新并安装,所以需要加入以下这些权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
dialog的上下文必须在activity里面
package com.nantian.bean;
public class UpdataInfo {
//版本号
private String version;
//下载地址
private String url;
//更新内容
private String description;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
UpdateVersion.java
package com.nantian.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import com.nantian.bean.UpdataInfo;
import com.nantian.myaands.R;
import android.app.AlertDialog;
import android.app.ProgressDialog;
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.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
import android.widget.Toast;
public class UpdateVersion {
private Context _content;
private UpdataInfo info;
private static final int UPDATA_CLIENT = 0;
private static final int GET_UNDATAINFO_ERROR = 1;
private static final int DOWN_ERROR = 2;
public UpdateVersion(Context _content) {
super();
this._content = _content;
}
public void startUpdate(){
CheckVersionTask task = new CheckVersionTask();
new Thread(task).start();
}
//handler用来处理不同的情况
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case UPDATA_CLIENT:
//对话框通知用户升级程序
showUpdataDialog();
break;
case GET_UNDATAINFO_ERROR:
//服务器超时
Toast.makeText(_content, "获取服务器更新信息失败", 1).show();
break;
case DOWN_ERROR:
//下载apk失败
Toast.makeText(_content, "下载新版本失败", 1).show();
break;
}
}
};
/*
* 从服务器获取xml解析并进行比对版本号
*/
public class CheckVersionTask implements Runnable{
public void run() {
try {
//从资源文件获取服务器 地址
String path = _content.getResources().getString(R.string.serverurl);
//包装成url的对象
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
InputStream is =conn.getInputStream();
//由服务器返回的流文件解析出UpdataInfo实体
info = getUpdataInfo(is);
//getVersionName()获取当前的版本号,详细见这个方法
if(info.getVersion().equals(getVersionName())){
Toast.makeText(_content, "版本一样不需要更新", 1).show();
}else{
Message msg = new Message();
msg.what = UPDATA_CLIENT;
handler.sendMessage(msg);
}
} catch (Exception e) {
// 待处理
Message msg = new Message();
msg.what = GET_UNDATAINFO_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}
/*
* 获取当前程序的版本号
*/
private String getVersionName() throws Exception{
//获取packagemanager的实例
PackageManager packageManager = _content.getPackageManager();
//getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(_content.getPackageName(), 0);
return packInfo.versionName;
}
/*
* 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)
*/
public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");//设置解析的数据源
int type = parser.getEventType();
UpdataInfo info = new UpdataInfo();//实体
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());//获取该文件的信息
}
break;
}
type = parser.next();
}
return info;
}
/*
*
* 弹出对话框通知用户更新程序
*
* 弹出对话框的步骤:
* 1.创建alertDialog的builder.
* 2.要给builder设置属性, 对话框的内容,样式,按钮
* 3.通过builder 创建一个对话框
* 4.对话框show()出来
*/
protected void showUpdataDialog() {
AlertDialog.Builder builer = new Builder(_content) ;
builer.setTitle("版本升级");
builer.setMessage(info.getDescription());
//当点确定按钮时从服务器上下载 新的apk 然后安装
builer.setPositiveButton("确定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
downLoadApk();
}
});
//当点取消按钮时进行登录
builer.setNegativeButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(_content, "暂时不想更新", 1).show();
}
});
AlertDialog dialog = builer.create();
dialog.show();
}
/*
* 从服务器中下载APK
*/
protected void downLoadApk() {
final ProgressDialog pd;//进度条对话框
pd = new ProgressDialog(_content);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下载更新");
pd.show();
new Thread(){
@Override
public void run() {
try {
File file = getFileFromServer(info.getUrl(), pd);
sleep(3000);
installApk(file);
pd.dismiss(); //结束掉进度条对话框
} catch (Exception e) {
Message msg = new Message();
msg.what = DOWN_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}}.start();
}
//从服务器得到更新文件,并且更新进度条
public 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);
conn.connect();
//获取到文件的大小
int filelength = conn.getContentLength();
pd.setMax(100);
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory(), "sh_mobile.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;
int currentlength = (int) (((float) total / filelength) * 100);
//获取当前下载量
pd.setProgress(currentlength);
}
fos.close();
bis.close();
is.close();
return file;
}
else{
return null;
}
}
//安装apk
protected void installApk(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//执行动作
intent.setAction(Intent.ACTION_VIEW);
//执行的数据类型
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
_content.startActivity(intent);
}
}
代码注释写的比较清楚
更新的时候只需要执行startUpdate()方法就可以了