Android 如何实现google天气

来源:互联网 发布:java面试三大框架ssm 编辑:程序博客网 时间:2024/06/05 09:48

    1、首先,在AndroidManifest.xml文件中添加权限,允许android访问internet,如下:


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

  1. 其次,通过经纬度获取Google天气的API。通过此API,将返回一个XML的文件,里面包含了Google提供的天气信息。
  2. 通过NodeList,获取相关节点的数据。
  3. 具体代码如下:

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);

}

}

 

原创粉丝点击