您的位置:首页 > 编程语言

关于利用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: