package com.altersoft.FoodMisClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
public class Update extends Activity {
public static float localVersion = 0;
public static float serverVersion = 0;
public ProgressDialog pBar;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.contact_manager); initGlobal();// Initialize the local version and server version checkVersion(); // Check whether the local version needs to be updated } public void initGlobal() { try { localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // Set the local version number serverVersion = 0; version("http://60.171.56.198:8000/Home /Version");// Download the version number information ReadXML();// Read the version number from the downloaded file and assign a value to the version number variable } catch (Exception ex) { ex.printStackTrace(); } }
public void version(final String url) { 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();// Get the data stream long length = entity.getContentLength();// Get the data stream length InputStream is = entity.getContent();// Get the data stream content FileOutputStream fileOutputStream = null; if (is != null) { File file = new File(
Environment.getExternalStorageDirectory()
+ "/version.xml");
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;//Bytes read from the input stream at a time Length
int count = 0;// total read length
while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch); count += ch; if (length > 0) {// If length>0 means there is still unfinished data length = length - ch; } }
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
void ReadXML() {
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
Document doc = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
// xml file 放到 assets目录中的
File f = new File(Environment.getExternalStorageDirectory()
+ "/version.xml");
InputStream is = new FileInputStream(f);
doc = docBuilder.parse(is);
// root element
Element root = doc.getDocumentElement();
// Do something here
// get a NodeList by tagname
NodeList nodeList = root.getElementsByTagName("string");
Element nd = (Element) nodeList.item(0);
// serverVersion = Integer.parseInt(nd.getNodeValue());
String s = nd.getChildNodes().item(0).getNodeValue().toString();
serverVersion = Float.parseFloat(s);
} catch (IOException e) {
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
} finally {
doc = null;
docBuilder = null;
docBuilderFactory = null;
}
}
public void checkVersion() {
if (localVersion < serverVersion) {
// 发现新版本,提示用户更新
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Software upgrade")
.setMessage("New version found, it is recommended to update and use immediately.")
.setPositiveButton("Update",
new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { pBar = new ProgressDialog (Update.this); pBar.setTitle("Downloading"); pBar.setMessage("Please wait..."); pBar.setProgressStyle
(ProgressDialog.STYLE_SPINNER); // The url here should be changed to the address of
the downloaded server downFile ("http://60.171.56.198:8000/Home/Download"); } }) .setNegativeButton("Cancel", new DialogInterface .OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog. dismiss(); } }); alert. create(). show();
}
}
void downFile(final String url) { 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();// get data stream long length = entity.getContentLength();// get data stream length InputStream is = entity.getContent();// get data stream content FileOutputStream fileOutputStream = null;
if (is != null) { File file = new File("/sdcard/update.apk"); fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1;/ / The length of bytes read from the input stream at a time int count = 0;// The length read in total while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch ); count += ch; if (length > 0) {// If length>0 means there is still unfinished data length = length - ch; } }
}
fileOutputStream.flush();
if (fileOutputStream != null) { fileOutputStream.close(); } down();// close the scroll bar and open the latest version installer just downloaded } catch (ClientProtocolException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace(); } } }.start(); } void down() { handler.post(new Runnable() { public void run() { pBar.cancel() ;
Toast.makeText(Update.this, "Download is complete, start the installation", Toast.LENGTH_LONG)
.show();
update();
}
});
}
void update() {// Open the updated installer
File file = new File("/sdcard/update.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent );
}
}
Also attach the version.xml file
<?xml version="1.0" encoding="UTF-8" ?>
<Versions>
<Version>
<versionCode>2.0</versionCode>
</Version>
</Versions>