在我创建天气小应用的时候首先要面对的问题是如何读取天气数据,我使用了weather.com.cn的公共接口作为我的天气数据来源,以下为加载url并读取网页上的数据(Json)代码:
String todayURL = getResources().getString(R.string.today_base_url) + cityId + ".html";
HttpGet todayHttpGet = new HttpGet(todayURL);
HttpResponse todayHttpResponse = httpClient.execute(todayHttpGet);
HttpEntity todayHttpEntity = todayHttpResponse.getEntity();
InputStream todayInputStream = todayHttpEntity.getContent();
BufferedReader todayBufferedReader = new BufferedReader(new InputStreamReader(todayInputStream));
String line = todayBufferedReader.readLine();
todayInputStream.close();
String today_weather_info = line;
Android中现在已经不能再主线程中运行,所以上述连接网络的代码应该在非UI线程中运行,因此创建多线程:
@Override
public void run() {
//联网的代码
}
}
在非UI线程中一般不能直接修改UI视图,因此使用Handler来传递消息,并在Handler中更新UI视图:Message msg = msgHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("TODAY_WEATHER_INFO", today_weather_info);
bundle.putString("CURRENT_DATE", currentDate);
bundle.putString("NOW_WEATHER_INFO", now_weather_info);
bundle.putString("FUTURE_WEATHER_INFO", future_weather_info);
msg.setData(bundle);
msgHandler.sendMessage(msg);
public Handler msgHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
String todayWeatherInfo = msg.getData().getString("TODAY_WEATHER_INFO");
String nowWeatherInfo = msg.getData().getString("NOW_WEATHER_INFO");
String futureWeatherInfo = msg.getData().getString("FUTURE_WEATHER_INFO");
date = msg.getData().getString("CURRENT_DATE");
//解析今日天气的JSON数据
JSONObject jsonTodayInfo = new JSONObject(todayWeatherInfo).getJSONObject("weatherinfo");
<city = jsonTodayInfo.getString("city");
//TextView setText等操作
}
}
Android官方培训中对于连接网络的说明:http://hukai.me/android-training-course-in-chinese/connectivity/network-ops/connecting.html