在android的许多应用中都有检测更新的功能,以下整理下实现这个功能的步骤,原理为服务端放置新版本的apk文件和apk版本信息,手机端或者服务端的版本信息然后与手机目前安装的版本进行比较并做相应的提示。
因为需要下载即向sd卡中写文件所以,需要开启读写权限,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
用一个activity实现:代码如下:
工具类:
public class AndroidUtils {
public static final String TAG="AndroidUtils";
public static final String UPDATE_SERVER="http://192.168.1.108:8080/androidApp";
public static final String UPDATE_APKNAME="/demo.apk";
//获取版本号
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo(
"com.app", 0).versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
return verCode;
}
//获取版本名称
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo(
"com.app", 0).versionName;
} catch (NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
return verName;
}
}
实现类:
public class Updater extends Activity {
private static final String TAG="Updater";
private int newVerCode=1;
private String newVerName="1.0.0";
private ProgressDialog pBar;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updater);
if (getServerVerCode()) {
int vercode = AndroidUtils.getVerCode(this); // 用到前面第一节写的方法
if (newVerCode > vercode) {
doNewVersionUpdate(); // 更新新版本
} else {
notNewVersionShow(); // 提示当前为最新版本
}
}
}
//获取服务器上的版本信息
private boolean getServerVerCode() {
try {
String xml=new ClientUtil().getVersionInfo();
Map<String,Object> map=ParseXmlUtil.parseAndroidVersionXml(xml);
newVerCode=Integer.parseInt(map.get("code").toString());
newVerName=map.get("name").toString();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (XmlRpcException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
@SuppressWarnings("unused")
private void notNewVersionShow() {
int verCode = AndroidUtils.getVerCode(this);
String verName = AndroidUtils.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append("\n已是最新版,无需更新!");
Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新")
.setMessage(sb.toString())// 设置内容
.setPositiveButton("确定",// 设置确定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).create();// 创建
// 显示对话框
dialog.show();
}
private void doNewVersionUpdate() {
int verCode = AndroidUtils.getVerCode(this);
String verName = AndroidUtils.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(", 发现新版本:");
sb.append(newVerName);
sb.append(" Code:");
sb.append(newVerCode);
sb.append(", 是否更新?");
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("软件更新")
.setMessage(sb.toString())
// 设置内容
.setPositiveButton("更新",// 设置确定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
pBar = new ProgressDialog(Updater.this);
pBar.setTitle("正在下载");
pBar.setMessage("请稍候...");
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downFile(AndroidUtils.UPDATE_SERVER + AndroidUtils.UPDATE_APKNAME);
}
})
.setNegativeButton("暂不更新",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// 点击"取消"按钮之后退出程序
finish();
}
}).create();// 创建
// 显示对话框
dialog.show();
}
//下载文件
public void downFile(final String url) {
Log.e(TAG, "begin download file"+Environment.getExternalStorageDirectory()+ AndroidUtils.UPDATE_APKNAME);
pBar.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(
Environment.getExternalStorageDirectory(),
AndroidUtils.UPDATE_APKNAME);
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
if (length > 0) {
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
Log.e(TAG, "finish download file");
finishDown();
} catch (ClientProtocolException e) {
e.printStackTrace();
errorDown();
} catch (IOException e) {
e.printStackTrace();
errorDown();
} catch (Exception e) {
e.printStackTrace();
errorDown();
}
}
}.start();
}
//正确下载完成并开始安装
public void finishDown() {
handler.post(new Runnable() {
public void run() {
pBar.cancel();
update();
}
});
}
//下载中出现错误
public void errorDown() {
handler.post(new Runnable() {
public void run() {
pBar.cancel();
showError("软件下载过程中出现错误,请您稍候再试!");
}
});
}
//提示错误
public void showError(String errorMsg){
Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新提醒")
.setMessage(errorMsg)// 设置内容
.setPositiveButton("确定",// 设置确定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).create();// 创建
// 显示对话框
dialog.show();
}
//准备安装
public void update() {
Log.e(TAG, "begin install file");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), AndroidUtils.UPDATE_APKNAME)),
"application/vnd.android.package-archive");
startActivity(intent);
}
}
为了保证apk能顺利覆盖安装,需要对apk文件进行签名,
可以参考这篇文章:
http://www.cnblogs.com/qianxudetianxia/archive/2011/04/09/2010468.html