您的位置:首页 > 移动开发 > Android开发

Android 如何实现google天气

2011-06-18 11:36 417 查看
    1、首先,在AndroidManifest.xml文件中添加权限,允许android访问internet,如下:

         <uses-permission android:name="android.permission.INTERNET"/> 

其次,通过经纬度获取Google天气的API。通过此API,将返回一个XML的文件,里面包含了Google提供的天气信息。

通过NodeList,获取相关节点的数据。

具体代码如下:

java代码:

    

public class GoogleWeather {
private Integer Latitude;//纬度
private Integer Longitude;//经度
private String url=null;
private String sTemp;//温度
 
GoogleWeather(Integer longi,Integer lati)
{
Latitude=lati;
Longitude=longi;
 
//http://www.google.com/ig/api?hl=zh-cn&weather=,,,30670000,104019996
url="http://www.google.com/ig/api?hl=en&weather=,,,"+Longitude+","+Latitude;
Log.d("log","url="+url);
}
 
public void getWeatherData() throws ClientProtocolException, IOException, ParserConfigurationException, FactoryConfigurationError, SAXException
{
DefaultHttpClient client = new DefaultHttpClient();
HttpUriRequest Request = new HttpGet(url);
HttpResponse Response = client.execute(Request);
HttpEntity Entity = Response.getEntity();
InputStream stream = Entity.getContent();
DocumentBuilder Builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = Builder.parse(new InputSource(stream));
NodeList n = doc.getElementsByTagName("current_conditions");
 
Log.d("log","Node Length="+n.getLength());
for (int i = 0; i < n.getLength(); i++)//遍列current_condition所有节点
{
//获取节点的天气数据
sTemp=n.item(i).getChildNodes().item(2).getAttributes().item(0).getNodeValue();
}
Log.d("log","sTemp="+sTemp);
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐