标签:
第一步:启动tomcat,在tomcat中加入如下json文件
{"version":"2.0","description":"我是最新的,来下载我把","apkurl":"http://192.168.1.103:8080/zaizaimobilesafe-2.0.apk"}
第二步:实现一个函数显示网络访问服务器获取服务器数据的功能函数
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函数以及主页面的代码
标签:
原文地址:http://my.oschina.net/zaizaiangels/blog/516261