我正在使用您正在寻找的相同功能。我在 MainActivity 的 OnCreate 上调用了 networkUpdate()。
- 该功能创建了单独的线程并在线获取最新版本号。
- 获取此二进制文件的版本号
- 在 toast 中显示自定义消息(新版本提醒)
在线文本文件
{"version":"1.2","message":"News version of XXX is available. Please download at Google Play"}
android中的源代码
private Handler m_handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
...............
m_handler = new Handler(); //for main thread
networkUpdate();
}
private void networkUpdate(){
Thread t = new Thread(new Runnable() {
@Override
public void run() { //heavy loading
ObjectMapper mapper = new ObjectMapper();
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://xxx/version.txt");
HttpResponse response = client.execute(request);
String retSrc = EntityUtils.toString(response.getEntity());
JsonNode networkJson = mapper.readTree(retSrc);
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
String networkVersion = networkJson.path("version").textValue();
if(Float.valueOf(version) < Float.valueOf(networkVersion)){
m_updateMessage = networkJson.path("message").textValue();
}
System.out.println(version + "v "+ networkVersion + " m " +networkJson.path("message").textValue());
} catch (Exception e) {
Log.e("network update", "read version json", e);
}
m_handler.post(new Runnable() {
public void run() { //main thread
if(m_updateMessage != null){
Toast.makeText(MainActivity.this, m_updateMessage, Toast.LENGTH_LONG).show();
}
} }); } }); t.start();
}