基於百度定位及天氣擷取的DEMO,天氣擷取demo
demo基於百度定位APIv4.0版、新浪天氣(不用查詢城市代碼)。
需求:
1、button實現觸發定位監聽和天氣捕獲
2、兩個textview 分別顯示詳細地址、天氣。
介面很簡陋,側重功能實現。
下面記錄下主要技術點:
1.百度定位
/** * 發起定位 */ public void requestLocationInfo() { setLocationOption(); if (mLocationClient != null && !mLocationClient.isStarted()) { mLocationClient.start(); } if (mLocationClient != null && mLocationClient.isStarted()) { mLocationClient.requestLocation(); } } /** * 設定相關參數 */ private void setLocationOption() { LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); // 開啟gps option.setCoorType("bd09ll"); // 設定座標類型 option.setServiceName("com.baidu.location.service_v2.9"); option.setPoiExtraInfo(true); option.setAddrType("all"); option.setPoiNumber(10); option.disableCache(true); mLocationClient.setLocOption(option); } /** * 監聽函數,有更新位置的時候,格式化成字串,輸出到螢幕中 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) { sendBroadCast(new ParcelableInfo("擷取失敗","擷取失敗")); return; } address=location.getAddrStr(); } public void onReceivePoi(BDLocation poiLocation) { if (poiLocation == null) { sendBroadCast(new ParcelableInfo("擷取失敗","擷取失敗")); return; } sendBroadCast(new ParcelableInfo(poiLocation.getDistrict(),poiLocation.getAddrStr())); } }
2.非同步擷取天氣資訊
非同步多線程一般處理方式有;1.handler處理:後續補充
2、AsyncTask:AsyncTask能夠更恰當和更簡單的去使用UI線程。這個類允許執行後台操作和展現結果在UI線程上,無需操縱線程和/或處理常式。AsyncTask的內部實現是一個線程池,每個背景工作會提交到線程池中的線程執行,然後使用Thread+Handler的方式調用回呼函數。
使用AsyncTask類,以下是幾條必須遵守的準則:
1) Task的執行個體必須在UI thread中建立
2) execute方法必須在UI thread中調用
3) 不要手動的調用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)這幾個方法
4) 該task只能被執行一次,否則多次調用時將會出現異常
doInBackground方法和onPostExecute的參數必須對應,這兩個參數在AsyncTask聲明的泛型參數列表中指定,第一個為doInBackground接受的參數,第二個為顯示進度的參數,第第三個為doInBackground返回和onPostExecute傳入的參數。
關鍵代碼:
package com.liucanwen.baidulocation;/* * 非同步多線程載入網路資訊,並更新UI * 通常有兩種方法:1、handler和Threat * 2、AsyncTask * 參考網址 http://www.cnblogs.com/dawei/archive/2011/04/18/2019903.html */import java.net.URL;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.liucanwen.baidulocation.util.UTF82GBK;import com.liucanwen.baidulocation.util.Weather;import android.os.AsyncTask;import android.widget.TextView;public class LoadWeatherAsyncTask extends AsyncTask<Object, Integer, String> { private TextView tv; String getweather; //表明對哪個textview進行非同步更新 public LoadWeatherAsyncTask(TextView tv) { this.tv = tv; } //準備工作,一般初始化textview @Override protected void onPreExecute() { } //注意:1) Task的執行個體必須在UI thread中建立 2) execute方法必須在UI thread中調用 ) @Override protected String doInBackground(Object... params) { return new Weather().getWeather((String)params[0]);//真正的非同步工作,從伺服器擷取xml資料並解析,但不能對UI操作 } protected void onPostExecute(String result) { // 該方法運行在UI線程內 tv.setText(result); }}
3.困擾好幾天的編碼問題導致返回天氣資料為null
由於之前直接將“廣州“的UTF8編碼傳入URL(ADT預設編碼UTF8)導致擷取不到天氣資料,
URL ur = new URL("http://php.weather.sina.com.cn/xml.php?city=" + str+ "&password=DJOYnieT8234jlsK&day=" + day);
後來發現,傳入的str需要為GB2312編碼資料。所以需要轉碼
new UTF82GBK().getCoding(str)
public String getCoding(String str) throws IOException{ String s1 = URLEncoder.encode(str, "gb2312"); return s1; }
public String getWeather(String str) { try { DocumentBuilderFactory domfac = DocumentBuilderFactory .newInstance(); DocumentBuilder dombuilder = domfac.newDocumentBuilder(); Document doc; Element root; NodeList books; // 瀏覽器中識別的是GBK編碼,直接輸入漢字是接收不到資料的 URL ur = new URL("http://php.weather.sina.com.cn/xml.php?city=" + new UTF82GBK().getCoding(str) + "&password=DJOYnieT8234jlsK&day=" + day); // 解析XML doc = (Document) dombuilder.parse(ur.openStream()); root = (Element) doc.getDocumentElement(); books = ((Node) root).getChildNodes(); for (Node node = books.item(1).getFirstChild(); node != null; node = node .getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("status1")) weather = node.getTextContent(); // 擷取天氣狀況 else if (node.getNodeName().equals("temperature1")) high = node.getTextContent(); // 擷取最高溫度 else if (node.getNodeName().equals("temperature2")) low = node.getTextContent(); // 擷取最低溫度 } } } catch (Exception e) { e.getMessage(); } String getweather = str + " " + weather + " " + low + "度~" + high + "度"; return getweather; }
4.Intent傳遞對象
需要從傳入MyApplication將City和address傳入到MainActivity中,將需要傳遞的資料封裝到LocationInfo類中。
使用intent傳遞對象的方法有兩種:
1、實現Serializable介面
2、實現Parcelable介面
我採用 實現Parcelable介面:
LocationInfo .java用於確定傳遞資料的資料模型
public class LocationInfo implements Serializable { private String city; private String address; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
/** * 實現了Parcelable介面的ParcelableInfo類: */import android.os.Parcel;import android.os.Parcelable;public class ParcelableInfo implements Parcelable { private String city; private String address; public ParcelableInfo() { } public ParcelableInfo(String city, String address) { this.city = city; this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public static final Parcelable.Creator<ParcelableInfo> CREATOR = new Creator<ParcelableInfo>() { @Override public ParcelableInfo createFromParcel(Parcel source) { ParcelableInfo parcelableInfo = new ParcelableInfo(); parcelableInfo.city = source.readString(); parcelableInfo.address = source.readString(); return parcelableInfo; } @Override public ParcelableInfo[] newArray(int size) { return new ParcelableInfo[size]; } }; @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeString(city); dest.writeString(address); } }
public void sendBroadCast(ParcelableInfo parcelableInfo) { stopLocationClient(); Intent intent = new Intent(MainActivity.LOCATION_BCR); //ParcelableInfo parcelableUser = new ParcelableInfo(city,address); //intent.putExtra("address", address); Bundle bundle = new Bundle(); bundle.putParcelable("parcelableInfo", parcelableInfo); intent.putExtras(bundle); sendBroadcast(intent); }
在MyApplication中發送
public void sendBroadCast(ParcelableInfo parcelableInfo) { stopLocationClient(); Intent intent = new Intent(MainActivity.LOCATION_BCR); Bundle bundle = new Bundle(); bundle.putParcelable("parcelableInfo", parcelableInfo); //將parcelableInfo對象封裝在bundle中 intent.putExtras(bundle); //intent傳遞bundle sendBroadcast(intent); }
在MainActivity中接收
parcelableInfo = intent.getParcelableExtra("parcelableInfo"); locInfo.setText("你所在的地址為:" + parcelableInfo.getAddress());
本人初學上路,語言表達不準確,見諒···
源碼地址:http://download.csdn.net/detail/xiejun1026/8411437