第一步:啓動tomcat,在tomcat中加入以下json文件
json
{"version":"2.0","description":"我是最新的,來下載我把","apkurl":"http://192.168.1.103:8080/zaizaimobilesafe-2.0.apk"} tomcat
第二步:實現一個函數顯示網絡訪問服務器獲取服務器數據的功能函數服務器
private void chackUpdate() { /*定義一個消息對象,做爲handler的形參進行數據的傳遞*/ final Message message = Message.obtain(); final long startTime = System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { try { /*在value文件夾中配置一個config.xml文件,存儲服務器的url,便於維護,getString得到,由於R.string.serviceurl表明的是一個整數是數據的一個標識,而不是數據自己*/ URL url = new URL(getString(R.string.serviceurl)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(4000); int code = connection.getResponseCode(); if (code == 200) { /*訪問成功*/ InputStream is = connection.getInputStream(); /*把流轉換成string*/ String result = StreamTools.readFromStream(is); Log.i(TAG, "聯網成功" + result); /*json解析*/ JSONObject object = new JSONObject(result); verison = (String) object.get("vsersion"); description = (String) object.get("description"); apkurl = (String) object.get("apkurl"); /*檢查是不是新版本*/ if (getVersionName().equals(verison)) { message.what = ENTER_HOME; /*版本一致,進入主頁面*/ } else { message.what = SHOW_UPDATE_DIALOG; /*更新新版本*/ } } } catch (MalformedURLException e) { message.what = URL_ERROR; e.printStackTrace(); } catch (IOException e) { message.what = NETWORK_ERROR; e.printStackTrace(); } catch (JSONException e) { message.what = JSON_ERROR; e.printStackTrace(); } finally { long endTime = System.currentTimeMillis(); /*運行了多少時間*/ long dTime = endTime - startTime; /*讓程序停留2秒*/ if (dTime < 4000) { try { Thread.sleep(4000 - dTime); } catch (InterruptedException e) { e.printStackTrace(); } } handler.sendMessage(message); } } }).start(); }
定義一個handler用於接收數據網絡
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_UPDATE_DIALOG:/*顯示升級的對話框*/ Log.i(TAG, "顯示升級對話框"); showUpdateDialog(); break; case ENTER_HOME:/*進入主頁面*/ enterHome(); break; case URL_ERROR:/*URL錯誤*/ enterHome(); Toast.makeText(getApplicationContext(), "URL錯誤", Toast.LENGTH_LONG).show(); break; case NETWORK_ERROR:/*網絡錯誤*/ enterHome(); Toast.makeText(getApplicationContext(), "網絡異常", Toast.LENGTH_LONG).show(); break; case JSON_ERROR:/*JSON解析錯誤*/ enterHome(); Toast.makeText(getApplicationContext(), "JSON解析錯誤", Toast.LENGTH_LONG).show(); break; default: break; } super.handleMessage(msg); } };
下一遍將給出entryHome函數以及主頁面的代碼ide