昨天我们大概描述了下Android中的XML解析,其实整个实现方式比较简单,可以参考anddev.org的例子和com.commonsware.android.internet例子,Google Weather API还包含了另一种方式根据经度、纬度方式获取天气信息。在T-Mobile G1中可以通过基于移动网络和GPS方式定位,粗略获取当前定位坐标可以下面代码获取。
LocationManager myLocationManager=null;
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location l = myLocationManager.getLastKnownLocation("network"); //这里使用myLocation方式获取。
String url = l.getLatitude() + "," + l.getLongitude(); //这里获取到了精度和维度,即使不用GPS我们基本上可以获取粗略的城市位置。这里获取的l.getLatitude()返回的是浮点型,我们需要处理下,比如获取的为31.174165,需要过滤掉“.”保留31174165即可,维度同理:我们提交下面的
http://www.google.com/ig/api?weather=,,,31174165,121433841 数据即可获取,这里我们使用了Google Weather API的精度维度方式获取,根据城市拼音名可以参考昨天的Android与XML解析一文,获取的内容如下:
<?xml version="1.0" ?>
– <xml_api_reply version="1">
– <weather module_id="0" tab_id="0">
– <forecast_information>
<city data="" />
<postal_code data="" />
<latitude_e6 data="31174165" />
<longitude_e6 data="121433841" />
<forecast_date data="2008-12-18" />
<current_date_time data="2008-12-18 18:00:00 +0000" />
<unit_system data="SI" />
</forecast_information>
– <current_conditions>
<condition data="晴" />
<temp_f data="52" />
<temp_c data="11" />
<humidity data="湿度: 44%" />
<icon data="/images/weather/sunny.gif" />
<wind_condition data="风向: 北、风速:14 (公里/小时)" />
</current_conditions>
– <forecast_conditions>
<day_of_week data="周四" />
<low data="4" />
<high data="12" />
<icon data="/images/weather/sunny.gif" />
<condition data="晴" />
</forecast_conditions>
– <forecast_conditions>
<day_of_week data="周五" />
<low data="7" />
<high data="15" />
<icon data="/images/weather/mostly_sunny.gif" />
<condition data="以晴为主" />
</forecast_conditions>
– <forecast_conditions>
<day_of_week data="周六" />
<low data="4" />
<high data="16" />
<icon data="/images/weather/sunny.gif" />
<condition data="晴" />
</forecast_conditions>
– <forecast_conditions>
<day_of_week data="周日" />
<low data="-6" />
<high data="5" />
<icon data="/images/weather/cn_cloudy.gif" />
<condition data="多云" />
</forecast_conditions>
</weather>
</xml_api_reply>
最后,Android开发网友情提示不要忘了加入定位相关的permission,这里还有一些细节问题,比如摄氏度和华氏度的转换以及时区问题,完整的工程源代码稍后提供下载。
RSS