android 获取天气预报

开发环境android4.0.3

网上有很多android获取天气预报的方法,但是由于android版本更新,在主线程在禁止访问网络权限,因此需要创建一个新的线程连接WebService。

android的WebService 应用soap简单对象协议,这里采用ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar开发包。

 

连接WebService主要接口如下:

  

public static SoapObject common(String methodName, HashMap<String, Object>map,
		String nameSpace, String endPoint)
{

	String soapAction = nameSpace + methodName; //指定WebService的命名空间和调用的方法名
	SoapObject rpc = new SoapObject(nameSpace,methodName ); //设置调用WebService就接口需要传入的参数
	if (null != map && map.size() > 0)
	{
		Iterator<Entry<String, Object>> iter = map.entrySet().iterator();  
		while (iter.hasNext()) {  
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) iter.next();  
			Object key = entry.getKey();  
			Object val = entry.getValue();
			rpc.addProperty(key.toString(), val.toString());
		}
	}
	 else
	{
		return null;
	
	}

	
	//生成调用WebService方法的SOAP	请求信息,并制定soap的版本
	SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
	envelope.bodyOut = rpc;
	//设置是否调用的doNet开发的WebService
	envelope.dotNet = true;
	envelope.setOutputSoapObject(rpc);

	//设置连接超时时间为20秒
	HttpTransportSE transport = new HttpTransportSE(endPoint, timeout);
	
	try{ //调用WebService
		
		transport.call(soapAction, envelope);
		
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		//return "Error:调用web services出错!"+e.getMessage(); 
	} 
	
	//获取返回的数据
	SoapObject soapObject = null;
	try {
		soapObject = (SoapObject) envelope.getResponse();
	} catch (SoapFault e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return  null;
	}

	System.out.println("soap" + soapObject.toString());
	return soapObject;
	}

 

解析WebService返回的XML的天气预报内容

private String  parseWeather(SoapObject detail)
{
	String date = detail.getProperty(6).toString();
	if (date.isEmpty())
	{
		
		return "false";
	}
	String weatherToday = "今天:" + date.split(" ")[0];
	weatherToday = weatherToday + "\n天气:" + date.split(" ")[1];
	weatherToday = weatherToday + "\n气温:"
			+ detail.getProperty(5).toString();
	weatherToday = weatherToday + "\n风力:"
			+ detail.getProperty(7).toString() + "\n";
	System.out.println("weatherToday is " + weatherToday);
  	return weatherToday;
}

 

获取天气预报的方法
public void  getWeather(String cityName)
{

	HashMap<String, Object> map = new HashMap<String, Object>();
	map.put("theCityName", cityName);
		
	SoapObject Result =  common( METHOD_NAME,map, NAMESPACE, URL);
	String ret = parseWeather(Result);
	 Message msg = new Message();                                
	 msg.what = this.MESSAGE_WEATHER;
	 Bundle bundle = new Bundle();    
	 bundle.putString("weatherdata", ret);
	 msg.setData(bundle);
     mHandler.sendMessage(msg);
	
}


 下面有整个工程的源代码myWeather

 

 


要在 Android 应用中获取天气预报,你可以使用一些第三方天气 API 来实现。以下是一个简单的示例,演示如何使用和解析天气 API 响应: 1. 添加以下依赖项到你的 app build.gradle 文件中: ``` dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.1' implementation 'com.google.code.gson:gson:2.8.6' } ``` 2. 在你的 Activity 或 Fragment 中,创建一个函数来获取天气数据: ```java private void getWeatherData(String city) { String apiKey = "your_api_key"; // 替换成你的 API Key String url = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseBody = response.body().string(); Gson gson = new Gson(); WeatherData weatherData = gson.fromJson(responseBody, WeatherData.class); // 处理天气数据 // 可以在这里更新 UI } } }); } ``` 3. 创建一个 WeatherData 类,用于解析 API 响应: ```java public class WeatherData { private Main main; private Weather[] weather; public Main getMain() { return main; } public Weather[] getWeather() { return weather; } public class Main { private double temp; public double getTemp() { return temp; } } public class Weather { private String main; private String description; public String getMain() { return main; } public String getDescription() { return description; } } } ``` 4. 在你的 Activity 或 Fragment 中,调用 getWeatherData() 函数,并传入城市名称: ```java getWeatherData("Beijing"); ``` 这个例子使用了 OpenWeatherMap API 来获取天气数据。你需要注册一个账户,获取你自己的 API Key,然后将它替换掉代码中的 "your_api_key"。当然,你也可以使用其他的天气 API,只需要根据 API 的文档来修改代码即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值