最近一直在搞公司分配給我的個人的一個小程序。搞了一段時間終於搞好了。
首先,是在服務器搞了一個services.xml
<?xml version="1.0" encoding="UTF-8"?> |
第二步是要去服務器找services.xml獲取裏面的version.
url = new URL("http://127.0.0.1:8080/update/data/update.xml");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
updateInfo = ParseXmlUtils.parseXml(connection.getInputStream());
第三步就是去解析這個xml
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* 解析Xml文件
* @author andrew
* 2012-04-05
* ParseXmlUtils.java
*/
public class ParseXmlUtils {
/**
* 通過InputStream 解析文件
* @param in
* @return
*/
public static UpdateInfo parseXml(InputStream in){
UpdateInfo updateInfo = new UpdateInfo();
/*InputStream 也可以是網絡,或者文件*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
/*以樹狀格式,存儲在內存中;比較耗費內存*/
Document doc = db.parse(in);
Element root = doc.getDocumentElement();
/*得到update的節點列表*/
NodeList resultNode = root.getElementsByTagName("info");
for(int i = 0; i < resultNode.getLength();i++){
Element res = (Element)resultNode.item(i);
updateInfo.setVersion(res.getElementsByTagName("version").item(0).getFirstChild().getNodeValue());
updateInfo.setUrl(res.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());
updateInfo.setDescription(res.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return updateInfo;
}
}
第四步比較當前系統的版本號跟在services.xml裏面得到的版本號是否一致。如果不一致就下載服務器的文件,如果一致就提醒用戶。
/**
* 比較版本是否相同 相同就提示"版本一樣 不需要更新"
*/
if(updateInfo.getVersion().trim().equals(VersionUtil.getVersionName())){
Toast.makeText(this, R.string.versions, Toast.LENGTH_SHORT).show();
}else{
download.showUpdateDialog(updateInfo);
}
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 android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
/**
* 下載
* @author andrew
* 2012-04-06
*
*/
public class Download extends Activity{
private Context mContext;
private Dialog downloadDialog;
private static final String savePath = "/sdcard/sub_sda1/";
private static final String saveFileName = savePath + "update.zip";
private ProgressBar mProgress;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private int progress;
private Thread downLoadThread;
private boolean interceptFlag = false;
UpdateInfo updateInfos;
/**
* 初始化
* @param context
*/
public Download(Context context) {
this.mContext = context;
}
/**
* 判斷是否要書寫進度條
*/
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWN_UPDATE:
mProgress.setProgress(progress);
break;
case DOWN_OVER:
updateSystem();
break;
default:
break;
}
};
};
/**
* 版本不一樣 就提示是否需要下載新的版本
* @param updateInfo
*/
public void showUpdateDialog(UpdateInfo updateInfo) {
updateInfos = updateInfo;
AlertDialog alertDialog = new AlertDialog.Builder(mContext)
.setTitle(R.string.tiptitle)
.setMessage(updateInfo.getDescription())
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDownloadDialog();
}
})
.setNegativeButton(R.string.cleck,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
alertDialog.show();
}
/**
* 顯示下載進度條
* 按取消按鍵可以取消下載
*/
private void showDownloadDialog(){
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle(R.string.system);
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.progress, null);
mProgress = (ProgressBar)v.findViewById(R.id.progress);
builder.setView(v);
builder.setNegativeButton(R.string.cleck, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
interceptFlag = true;
}
});
downloadDialog = builder.create();
downloadDialog.show();
updateSystem();
// download();
}
/**
* 下載更新系統文件
* @param url
*/
private void download(){
downLoadThread = new Thread(mdownApkRunnable);
downLoadThread.start();
}
/**
* 利用線程下載更新文件
*/
private Runnable mdownApkRunnable = new Runnable() {
@Override
public void run() {
try {
URL url = new URL(updateInfos.getUrl().trim());
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if(!file.exists()){
file.mkdir();
}
String apkFile = saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[1024];
try{
do{
int numread = is.read(buf);
count += numread;
progress =(int)(((float)count / length) * 100);
//更新進度
mHandler.sendEmptyMessage(DOWN_UPDATE);
fos.write(buf,0,numread);
}while(!interceptFlag);//點擊取消就停止下載.
}catch(Exception e){
e.printStackTrace();
}finally{
Message message2=new Message();
message2.what=2;
mHandler.sendMessage(message2);
//下載完成後關閉下載進度條
downloadDialog.dismiss();
}
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
};
/**
* 更新系統
* 按確定按鈕就可以更新系統
* 按取消按鈕就可以取消更新系統
*/
private void updateSystem(){
AlertDialog updateDialog = new AlertDialog.Builder(mContext)
.setTitle(R.string.tishi)
.setMessage(R.string.updatesystem)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
updateDialog.show();
}
}