Android 天氣預報入門
一款優(yōu)秀的天氣播報軟件,除了在功能上要達到實時準確預報天氣之外,其自帶的桌面天氣插件還能起到美化桌面的作用,今天小編為大家介紹一下天氣預報的簡單寫法,讓您時時刻刻都能夠第一時間了解最新的天氣動態(tài)。
1.Android的天氣預報的應用還是挺多的,基于JSON和WebServ的均可。
首先我們來介紹基于JSON解析的天氣預報的開發(fā)
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;
- }
- }
一款簡單的天氣預報就做好了!如果你是一個愛學習的人,并耐心的看完了本文的話,希望本文對你有所幫助!