原理就是从服务器获取版本号和本得apk的版本号对比更新;
//检查更新
Activity activity = this;
while(activity.getParent()!=null){
activity = activity.getParent();
}
new UpdateManager(activity, true).checkUpdate();
下面是UpdateManager.java类:
package com.tzj.update;
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 java.util.Locale;
import java.util.Map;
import org.json.JSONObject;
import com.tzj.uitl.NetUtil;
import android.app.Activity;
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.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
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;
public class UpdateManager
{
//下载中...
private static final int DOWNLOAD = 1;
//下载完成
private static final int DOWNLOAD_FINISH = 2;
//保存解析的XML信息
Map<String , String> mHashMap;
//下载保存路径
private String mSavePath;
//记录进度条数量
private int progress;
//是否取消更新
private boolean cancelUpdate = false;
//上下文对象
private Context mContext;
//进度条
private ProgressBar mProgressBar;
//更新进度条的对话框
private Dialog mDownloadDialog;
private boolean isShowDialog;
private String msg;
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch(msg.what){
//下载中。。。
case DOWNLOAD:
//更新进度条
System.out.println(progress);
mProgressBar.setProgress(progress);
break;
//下载完成
case DOWNLOAD_FINISH:
// 安装文件
installApk();
break;
}
};
};
public UpdateManager(Context context, boolean isShowDialog) {
super();
this.mContext = context;
this.isShowDialog = isShowDialog;
}
/**
* 检测软件更新
*/
public void checkUpdate() {
new Thread(new Runnable() {
@Override
public void run() {
if (isUpdate()) {
//显示提示对话框
showNoticeDialog();
} else {
if(isShowDialog){
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
if(!NetUtil.isNetworkAvailable(mContext)){
Toast.makeText(mContext,"无适用的网络", 1).show();
}else{
Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
}).start();
}
private void showNoticeDialog() {
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
//构造对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle(R.string.soft_update_title);
builder.setMessage(msg);
handler.postDelayed(new Runnable() {
@Override
public void run() {
noticeDialog.dismiss();
showDownloadDialog();
}
}, 30000);*/
//更新
builder.setPositiveButton("确定更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 显示下载对话框
showDownloadDialog();
}
});
// 稍后更新
builder.setNegativeButton("稍后更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
});
}
private void showDownloadDialog() {
// 构造软件下载对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle(R.string.soft_updating);
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.softupdate_progress, null);
mProgressBar = (ProgressBar) view.findViewById(R.id.update_progress);
builder.setView(view);
/*builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});*/
mDownloadDialog = builder.create();
mDownloadDialog.show();
//下载文件
downloadApk();
}
/**
* 下载APK文件
*/
private void downloadApk() {
// TODO Auto-generated method stub
// 启动新线程下载软件
new DownloadApkThread().start();
}
/**
* 检查软件是否有更新版本
* @return
*/
public boolean isUpdate() {
// 获取当前软件版本
double versionCode = Double.valueOf(getVersionCode(mContext));
try {
mHashMap = parseServerUrl();
} catch (Exception e) {
e.printStackTrace();
}
if(null != mHashMap && mHashMap.size() >0) {
double serviceCode = Double.valueOf(mHashMap.get("version"));
//版本判断
if(serviceCode > versionCode) {
return true;
}
}
return false;
}
//从服务器获取版本号;
private Map<String, String> parseServerUrl(){
Map<String, String> hashMap = new HashMap<String, String>();
URL url = null;
HttpURLConnection httpurlconnection = null;
try
{
Locale locale = mContext.getResources().getConfiguration().locale;
String language = locale.getLanguage();
if (language.endsWith("zh"))
url = new URL("http://#######/chinese/android/update.php");
else
url = new URL("http://#######/android/update.php");
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
int code = httpurlconnection.getResponseCode();
Log.i("http_post", code+"");
InputStream inputStream = httpurlconnection.getInputStream();
byte[] buffer = new byte[5000];
inputStream.read(buffer);
final String bufferStr = new String(buffer);
//json解析;
JSONObject jo = new JSONObject(bufferStr);
String version = jo.getString("version");
String downloadUrl = jo.getString("url");
msg = jo.getString("msg");
/*
int start = bufferStr.indexOf("<config_version>");
int end = bufferStr.indexOf("</config_version>");
int start2 = bufferStr.indexOf("<download_url>");
int end2 = bufferStr.indexOf("</download_url>");
int start3 = bufferStr.indexOf("<version_description>");
int end3 = bufferStr.indexOf("</version_description>");
String version = bufferStr.substring(start+16, end);
String downloadUrl = bufferStr.substring(start2+14,end2);
msg = bufferStr.substring(start3+21,end3);
*/
System.out.println("1111111111111 66666666 version = " +version);
System.out.println("11111111116666666666 downloadUrl= " +downloadUrl);
System.out.println("111111111111666666 msg = " +msg);
String name = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1, downloadUrl.length());
hashMap.put("url", downloadUrl);
hashMap.put("version", version);
hashMap.put("name", name);
Log.i("http_post", bufferStr);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(httpurlconnection!=null)
httpurlconnection.disconnect();
}
return hashMap;
}
/**
* 获取软件版本号
* @param context
* @return
*/
private String getVersionCode(Context context) {
// TODO Auto-generated method stub
String versionName="";
// 根据软件的包名获取软件版本号,对应AndroidManifest.xml下android:versionCode
try {
versionName = context.getPackageManager().getPackageInfo(
"com.example.update", 0).versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return versionName;
}
/**
* 下载文件线程
* @author Administrator
*
*/
private class DownloadApkThread extends Thread {
@Override
public void run() {
try
{
//判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
// 获取SDCard的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
URL url = new URL(mHashMap.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, mHashMap.get("name"));
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do
{
int numread = is.read(buf);
count += numread;
// 计算进度条的位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0)
{
// 下载完成
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();
}
}
/**
* 安装APK文件
*/
private void installApk()
{
File apkfile = new File(mSavePath, mHashMap.get("name"));
if (!apkfile.exists())
{
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
}