一款优秀的天气播报软件,除了在功能上要达到实时准确预报天气之外,其自带的桌面天气插件还能起到美化桌面的作用,今天小编为大家介绍一下天气预报的简单写法,让您时时刻刻都能够第一时间了解最新的天气动态。
1.Android的天气预报的应用还是挺多的,基于JSON和WebServ的均可。
首先我们来介绍基于JSON解析的天气预报的开发
2.这需要寻找到合适的数据源。
这里使用的是http://www.weather.com.cn/(中央气象局)的数据信息。可通过 m.weather.com.cn/data/101010100.html或者www.weather.com.cn/data/cityinfo /101010100.html查看到北京的天气信息。
3.接下来就是对JSON数据的解析
- package com.cater.weather;
- import java.io.IOException;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- 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.JSONException;
- import org.json.JSONObject;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.EditText;
- import android.widget.TextView;
- public class WeatherReportActivity extends Activity
- {
- private final static String url = "http://m.weather.com.cn/data/101010100.html";
- private HttpClient httpClient;
- private HttpResponse httpResponse;
- private HttpGet httpGet;
- private EditText editText;
- private TextView textView;
- private String today;
- private String dayofweek;
- private String city;
- private int ftime;
- private String template;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- editText = (EditText) findViewById(R.id.editText1);
- textView = (TextView) findViewById(R.id.textView1);
- httpClient = new DefaultHttpClient();
- parseString(getRequest(url));
- editText.setText(getRequest(url));
- textView.setText("城市:" + city + "\n"
- +"温度:" + template + "\n"
- +"星期:" + dayofweek + "\n"
- +"时间:" + ftime + "\n"
- +"日期:" + today + "\n");
- }
- private String getRequest(String uri)
- {
- httpGet = new HttpGet(uri);
- String result = "";
- try
- {
- httpResponse = httpClient.execute(httpGet);
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
- {
- result = EntityUtils.toString(httpResponse.getEntity());
- return result;
- }
- }
- catch (ClientProtocolException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- private String parseString(String str)
- {
- try
- {
- JSONObject jsonObject = new JSONObject(str).getJSONObject("weatherinfo");
- today = jsonObject.getString("date_y");
- dayofweek = jsonObject.getString("week");
- city = jsonObject.getString("city");
- ftime = jsonObject.getInt("fchh");
- template = jsonObject.getString("temp1");
- }
- catch (JSONException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- }
一款简单的天气预报就做好了!如果你是一个爱学习的人,并耐心的看完了本文的话,希望本文对你有所帮助!