android 得到本地天气情况

今天项目新添加了得到本地当天的温度,湿度,pm2.5的值的需求,研究了下,记下劳动成果,为码农少走弯路做贡献。

思路如下:

1.得到手机的外网ip(http://ip-api.com/json)

2.得到本地信息:省份和城市名(http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=)

3.根据省份城市名拿到城市代码(https://code.csdn.net/snippets/621277/master/blog_20150317_1_5052706/raw)

4.根据城市代码得到天气情况
(http://wthrcdn.etouch.cn/WeatherApi?citykey=)

当然天气情况里面有很多这里只拿温度,湿度和pm2.5

具体代码如下:

package com.smart.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class WeatherCondition {

	 public  static String getIpUrl = "http://ip-api.com/json";
	 public  String getAddress = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
	 public  String cityCode = "https://code.csdn.net/snippets/621277/master/blog_20150317_1_5052706/raw";
	 public  String weatherUrl = "http://wthrcdn.etouch.cn/WeatherApi?citykey=";
//	 http://m.weather.com.cn/mweather/101280601.shtml
	 private  String locaInfo;
	 public  SearchWeatherListner weatherListner;
	 private String city ;

	 public interface SearchWeatherListner{

		 public void weatherInfo(String city,String tem,String shidu,String pm);
		 public void error(Exception e);

	 }

	    public WeatherCondition(SearchWeatherListner weatherListner) {
		super();
		this.weatherListner = weatherListner;
	}

		public void getWebIp(final String urlStr) {
	        new Thread() {
	            public void run() {
	                String strForeignIP = "";
	                try {
	                    URL url = new URL(urlStr);

	                    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

	                    String s = "";
	                    StringBuffer sb = new StringBuffer("");
	                    while ((s = br.readLine()) != null) {
	                        sb.append(s + "\r\n");
	                    }
	                    br.close();

	                    String webContent = "";
	                    webContent = sb.toString();
	                    System.out.println("webContent:"+webContent);
	                    if(urlStr.equals(getIpUrl)){//1 得到ip
	                    	getIp(webContent);
	                    }else if(urlStr.equals(cityCode)){//3 得到所有cityCode
	                    	getAddress(locaInfo,new JSONObject(webContent));
	                    }
	                    else if(urlStr.indexOf(weatherUrl)!=-1){//4 得到天气情况
	                    	 webContent = sb.toString();
	                    	 parserXml(webContent);
	                    }
	                    else{//2 得到本地信息
	                    	locaInfo =webContent;
	                    	getWebIp(cityCode);
	                    }
	                } catch (Exception e) {
	                	weatherListner.error(e);
	                    e.printStackTrace();
	                }
	            };
	        }.start();

	    }
		public void parserXml(String str){

			String wendu = str.substring(str.indexOf("<wendu>"), str.indexOf("</wendu>")).replace("<wendu>", "");
			String shidu = str.substring(str.indexOf("<shidu>"), str.indexOf("</shidu>")).replace("<shidu>", "");
			String pm25 = str.substring(str.indexOf("<pm25>"), str.indexOf("</pm25>")).replace("<pm25>", "");
			System.out.println("wendu:"+wendu+" shidu:"+shidu+" pm25:"+pm25);
	        weatherListner.weatherInfo(city,wendu, shidu, pm25);
		}

	    public void getAddress(String str,JSONObject cityJson){
	    	try {
				JSONObject json = new JSONObject(str);
				String country = json.getString("country");
				String province = json.getString("province");
				city = json.getString("city");
				JSONArray ja_province = cityJson.getJSONArray("城市代码");
				for(int i=0;i<ja_province.length();i++){
					JSONObject jo_province =  ja_province.getJSONObject(i);
					if(jo_province.getString("省").equals(province)){
						JSONArray ja_city = jo_province.getJSONArray("市");
						for(int j=0;j<ja_city.length();j++){
							JSONObject jo_city = ja_city.getJSONObject(j);
							if(jo_city.getString("市名").equals(city)){
								String code = jo_city.getString("编码");
								getWebIp(weatherUrl+code);
								System.out.println("code:"+code);
								break;
							}

						}

						break;
					}

				}

			} catch (JSONException e) {
				weatherListner.error(e);
				e.printStackTrace();
			}
	    }

	    public void getIp(String str){
	    	try {
				JSONObject json = new JSONObject(str);
				String ip = json.getString("query");
				getWebIp(getAddress+ip);
			} catch (JSONException e) {
				weatherListner.error(e);
				e.printStackTrace();
			}

	    }

}

代码调用该类 new WeatherCondition(this).getWebIp(WeatherCondition.getIpUrl);

并监听WeatherCondition.SearchWeatherListner改接口

时间: 2024-08-25 15:41:03

android 得到本地天气情况的相关文章

Android Mediaplayer本地音乐播放器(绑定服务)

本文章介绍MediaPlayer本地音乐播放器,而当应用程序不再位于前台且没有正在使用它的活动时,为了确保音频继续播放,我们需要建立一个服务Service. Activity与绑定服务Service之间的交互是本文章的重点(这里需要说明一点的是,Activity不能直接访问服务对象中的方法,所以才有了我们一下的介绍,这也是为服务的安全等方面的考虑). 直接上代码: 布局文件:activity_main: <LinearLayout xmlns:android="http://schemas

Android jni本地编程入门

在某些情况下,java编程已经不能满足我们的需要,比如一个复杂的算法处理,这时候就需要用到jni技术: jni : java native interface jni 其实就是java和c/cpp之间进行通信的一个接口规范,java可以调用c/cpp里面的函数,同样,c/cpp也可以调用java类的方法: jni开发工具ndk的安装:在最新的ndk版本中,安装ndk很简单,只需要装ndk的路径配置到系统环境变量中即可:在编译的时候,进入工程根目录:执行命令  ndk-build  即可完成编译:

hdoj1437 -- 天气情况

天气情况 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 707    Accepted Submission(s): 285 Problem Description 如 果我们把天气分为雨天,阴天和晴天3种,在给定各种天气之间转换的概率,例如雨天转换成雨天,阴天和晴天的概率分别为0.4,0.3,0.3.那么在雨天 后的第二天出现雨天,阴

hdu 1437 天气情况【概率DP】

天气情况 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 638    Accepted Submission(s): 257 Problem Description 如果我们把天气分为雨天,阴天和晴天3种,在给定各种天气之间转换的概率,例如雨天转换成雨天,阴天和晴天的概率分别为0.4,0.3,0.3.那么在雨天后的第二天出现雨天,阴天和

webService获取电话号归属地和获取天气情况步骤,及创建属于自己的webservice

一.什么是Web服务 Web服务是一种可以用来解决跨网络应用集成问题的开发模式,目的是保证不同平台的应用服务可以互操作 二.Web服务的三个核心 Soap: SOAP(Simple Object Access Protocol,简单对象访问协议)是一个基于xml的协议,用于在分步的应用程序都可以识别.另外,SOAP本身没有定义任何程序语言,这使得SOAP能够以消息的形式传递到各种远程系统中. SOAP所使用的传输协议,可以是HTTP,SMTP,POP3,JMS. SOAP包括了4部分: 01."

python gui临时文件天气情况 这个urls.py源文件

# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' """ 这是一个简单的查询工具,是由pyqt+python+qt设计器制作而已的小工具 版本: ''' python2.7.8 pyqt4.10 ''' 操作系统;'windows7 64bit',中文 作者:空白 博客地址:http://www.cnblogs.com/mhxy13867806343/  and  https://github.

android docs本地帮助文档打开特别慢的解决方法

1.断网,使用IE打开 2.使用火狐浏览器脱机浏览 android docs本地帮助文档打开特别慢的解决方法,布布扣,bubuko.com

Android -- 打开本地图片且显示路径

背景                                                                                          代码                                                                                           先上布局文件: <LinearLayout xmlns:android="http://schemas.android.co

C# Winform 获取天气情况

WebServices(http://www.webxml.com.cn/WebServices/WeatherWebService.asmx)来实现天气预报,该天气预报 Web 服务,数据来源于中国气象局 http://www.cma.gov.cn/ ,数据每2.5小时左右自动更新一次,准确可靠.包括 340 多个中国主要城市和 60 多个国外主要城市三日内的天气预报数据. private void buttonWeather_Click_1(object sender, EventArgs