关于利用url动态获取天气的信息以及各个城市天气的id代码
2015-07-31 10:29
603 查看
思路:通过开启一个新的线程,线程根据url地址,不断的获去网上天气的动态的信息,然后将获取到的信息通过handler传递给oncreate方法,这样程序执行的时候就自动的显 示了天气信息 handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); JSONObject object = (JSONObject) msg.obj; try { tv_weather.setText(object.getString("city")+" "+object.getString("weather")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; weatherTimer = new Timer(); tv_weather=(TextView) findViewById(R.id.tv_weather); weatherTimer.schedule(new TimerTask() {//开启Timer每隔30s就获取信息 public void run() { String weatherUrl = "http://www.weather.com.cn/data/cityinfo/101010100.html"; weatherJson = queryStringForGet(weatherUrl); try { JSONObject jsonObject = new JSONObject(weatherJson); JSONObject weatherObject = jsonObject .getJSONObject("weatherinfo"); //JSONObject tempObject=new JSONObject(TempText).getJSONObject("weatherinfo"); Message message = new Message(); message.obj = weatherObject; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); } } }, 0, 20000);// delay=2000毫秒 后执行该任务 } //查询网络 private String queryStringForGet(String url) { HttpGet request = new HttpGet(url); String result = null; try { HttpResponse response = new DefaultHttpClient().execute(request); if (response.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); return result; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
相关文章推荐
- 初识volatite
- Java 内存与堆栈
- django 中间件记录所有请求及请求执行时间
- [转]spring4.x注解概述
- asp.net WebApi不能接收到Put和Delete请求,试图发送Put和Delete请求时得到405异常
- 第一次接触javaweb的新手认识
- C#6.0语法糖剖析(一)
- Spring之旅
- C++对象内存布局初探
- C语言注意点
- 关于Thinkphp的日志写入
- struts2使用response和request功能
- java集合浅谈(一)
- _sntprintf
- C++中的 extern "C"
- django 模板(template)中操作 python tuple
- 设置eclipse的文字编码格式
- 清除MyEclipse保存的svn账户信息
- Eclipse编译打包时报Conversion to Dalvik format failed with error 1 错误的解决方式
- 【python】 [基础] 数据类型,字符串和编码