关于利用url动态获取天气的信息以及各个城市天气的id代码

这篇博客介绍了一个通过新开线程和Handler机制,定时从指定URL获取天气信息并在应用中显示的方法。代码示例中,每30秒更新一次天气数据,解析JSON对象并更新UI。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:通过开启一个新的线程,线程根据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;
 	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值