注:参考http://blog.csdn.net/harvic880925/article/details/25191159 大大的代码,它使用的PHP服务器,由于本人服务器是ASP.NET的,so 稍作更改!
ASP.NET服务器代码
Service.amsx
[WebMethod(Description = "获取App版本号")]
public string ReturnSoftVcode()
{
return dbOperation.ReturnSoftVcode();
}
Function
/// <summary>
/// 返回app当前版本号
/// </summary>
/// <returns></returns>
public string ReturnSoftVcode()
{
string vcode ="";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("\\" + "version/VCode.xml")); //加载xml
XmlNodeList NodeList = xmlDoc.SelectNodes("/VCode");
vcode = NodeList[0].InnerText;
return vcode;
}
Android 代码
private DBUtil dbUtil;
Handler m_mainHandler;
ProgressDialog m_progressDlg;
long m_newVerCode; //最新版的版本号
String m_newVerName; //最新版的版本名
String m_appNameStr; //下载到本地要给这个APP命的名字
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
……………………
///软件更新function value
m_mainHandler = new Handler();
m_progressDlg = new ProgressDialog(this);
m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
m_progressDlg.setIndeterminate(false);
m_appNameStr = "SinotransContractSys.apk";
///
dbUtil = new DBUtil();
new MyThread_GetVCode().start();
}
public class myThreadToGetUserInfor extends Thread {
public void run() {
getUserInforData();
}
}
public class MyThread_GetVCode extends Thread {
public void run() {
String tempstrlist = dbUtil.ReturnSoftVcode();
if(tempstrlist != null)
{
int verCode = Common.getVerCode(getApplicationContext());
int currentCode = Integer.parseInt(tempstrlist);
Message message = new Message();
if(verCode<currentCode)
{
message.what = 3;
}
else
{
// message.what = 4;
}
mHandler.sendMessage(message);
}
}
}
/**
* 提示更新新版本
*/
private void doNewVersionUpdate() {
int verCode = Common.getVerCode(getApplicationContext());
String verName = Common.getVerName(getApplicationContext());
String str= "当前版本:"+verName+"/n,发现新版本,是否更新?";
Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新").setMessage(str)
// 设置内容
.setPositiveButton("更新",// 设置确定按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
m_progressDlg.setTitle("正在下载");
m_progressDlg.setMessage("请稍候...");
downFile(Common.UPDATESOFTADDRESS); //开始下载
}
})
.setNegativeButton("暂不更新",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// 点击"取消"按钮之后退出程序
}
}).create();// 创建
// 显示对话框
dialog.show();
}
/**
* 提示当前为最新版本
*/
private void notNewVersionDlgShow()
{
int verCode = Common.getVerCode(this);
String verName = Common.getVerName(this);
String str="当前版本:"+verName+" Code:"+verCode+",/n已是最新版,无需更新!";
Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新")
.setMessage(str)// 设置内容
.setPositiveButton("确定",// 设置确定按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).create();// 创建
// 显示对话框
dialog.show();
}
private void downFile(final String url)
{
m_progressDlg.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();
m_progressDlg.setMax((int)length);//设置进度条的最大值
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(
Environment.getExternalStorageDirectory(),
m_appNameStr);
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) {
m_progressDlg.setProgress(count);
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
down(); //告诉HANDER已经下载完成了,可以安装了
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 告诉HANDER已经下载完成了,可以安装了
*/
private void down() {
m_mainHandler.post(new Runnable() {
public void run() {
m_progressDlg.cancel();
update();
}
});
}
/**
* 安装程序
*/
void update() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), m_appNameStr)),
"application/vnd.android.package-archive");
startActivity(intent);
}
//Common.java
package com.bottle.stockmanage;
/**
* @author harvic
* @date 2014-5-7
* @address http://blog.csdn.net/harvic880925
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
public class Common {
public static final String SERVER_IP="http://10.0.2.2:2105/";
//public static final String SERVER_IP = "http://222.134.69.195:1234/";
public static final String UPDATESOFTADDRESS=SERVER_IP+"version/SinotransApp.apk";//软件更新包地址
/**
* 获取软件版本号
* @param context
* @return
*/
public static int getVerCode(Context context) {
int verCode = -1;
try {
//注意:"com.example.try_downloadfile_progress"对应AndroidManifest.xml里的package="……"部分
verCode = context.getPackageManager().getPackageInfo(
"com.sinotrans.sinotransappv01", 0).versionCode;
} catch (NameNotFoundException e) {
Log.e("msg",e.getMessage());
}
return verCode;
}
/**
* 获取版本名称
* @param context
* @return
*/
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo(
"com.sinotrans.sinotransappv01", 0).versionName;
} catch (NameNotFoundException e) {
Log.e("msg",e.getMessage());
}
return verName;
}
}
//参考:http://blog.csdn.net/harvic880925/article/details/25191159