Đoạn code sau đây mình lấy từ chương trình OptiNews (định danh là vn.zerox.optinews, các bạn sẽ thay bằng cái khác):
Tạo thread để check phiên bản:
Mã:
Thread thr = new LoadVersion(); thr.start();
Mã:
private class LoadVersion extends Thread { @Override public void run() { handler.sendEmptyMessage(0); try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet("http://market.android.com/details?id=vn.zerox.optinews"); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); html = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { html = null; } handler.sendEmptyMessage(1); } }
Mã:
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (oncreate) break; pd = new ProgressDialog(MainCategory.this); pd.setMessage("Kiểm tra cập nhật..."); pd.setCancelable(false); Window window = pd.getWindow(); //window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL); window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); pd.show(); break; case 1: if (!oncreate) pd.dismiss(); if (html == null) { if (!oncreate) Toast.makeText(MainCategory.this, "Lỗi truy cập thông tin !", Toast.LENGTH_SHORT).show(); } else { int i = html.indexOf("<dt>Current Version:</dt><dd>"); int j = html.indexOf("</dd>",i+29); if (i == -1 || j == -1) { Toast.makeText(MainCategory.this, "Lỗi truy cập thông tin phiên bản !", Toast.LENGTH_SHORT).show(); break; } String ver = html.substring(i+29, j); float nver = Float.parseFloat(ver); String cur = "1.0"; try { cur = getPackageManager().getPackageInfo(getPackageName(),0).versionName; } catch (NameNotFoundException e) {} float ncur = Float.parseFloat(cur); String text; if (ncur >= nver) { if (oncreate) break; text = "Bạn đang dùng phiên bản mới nhất !"; } else text = "Hiện đã có phiên bản mới là " + ver + " !"; AlertDialog.Builder dialog = new AlertDialog.Builder(MainCategory.this); dialog.setTitle("Kiểm tra cập nhật"); dialog.setMessage(text); dialog.setNeutralButton("Đóng", null); dialog.create().show(); } break; default: super.handleMessage(msg); } } };
(Vì trên Market không hiển thị VersionCode nên mình phải dùng VersionName)
No comments:
Post a Comment