连接服务器更新操作

来源:互联网 发布:黑马软件培训机构 编辑:程序博客网 时间:2024/05/22 13:08

1.新建一个线程

new Thread(new checkVersionTask()).start();

2.实现Runable

private class checkVersionTask implements Runnable {@Overridepublic void run() {SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);boolean isupdate = sp.getBoolean("update", true);if (!isupdate) {loadMainUI();return;}long startime = System.currentTimeMillis();Message msg = Message.obtain();try {URL url = new URL(getResources().getString(R.string.serverurl));HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("GET");httpURLConnection.setConnectTimeout(2000);int code = httpURLConnection.getResponseCode();if (code == 200) {InputStream is = httpURLConnection.getInputStream();UpdateInfo info = UpdateInfoParser.getUpdateInfo(is);if (info == null) {// xml解析失败msg.what = PARSE_XML_ERROR;} else {// xml解析成功msg.what = PARSE_XML_SUCCESS;}} else {msg.what = SERVER_ERROR;}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();msg.what = URL_ERROR;} catch (NotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();msg.what = URL_ERROR;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();msg.what = NETWORK_ERROR;}handler.sendMessage(msg);}}

3.消息机制处理


0 0
原创粉丝点击