編輯:關於 Android 程式設計
本文介紹如何借助 Google 地圖服務,通過用戶當前的經度與緯度反查(reverse geocode)出所在城市。
整體流程分為兩步:先通過 LocationManager 獲取當前的經緯度坐標,再把坐標提交給地圖服務接口,解析返回的 XML 或 JSON 數據,從中提取城市名稱。由於網絡請求屬於耗時操作,需放到子線程中執行。
通過 getLastKnownLocation 取得最近一次已知位置,GPS 不可用時退回網絡定位:
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation == null)
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
若只需要獲取一次城市信息而非實時跟蹤,可以註釋掉 requestLocationUpdates 的實時監聽部分,直接使用最近位置即可。
public void start() {
if (currentLocation != null) {
new Thread() {
public void run() {
String temp = reverseGeocode(currentLocation);
if (temp != null && temp.length() >= 2)
city = temp;
}
}.start();
}
}
reverseGeocode 方法拼接經緯度到 Google 地圖接口的請求 URL,通過 HttpURLConnection 發送請求,再用 SAX 解析返回的 XML:
String url = "https://maps.google.com/maps/geo?q="
+ Double.toString(loc.getLatitude()) + ","
+ Double.toString(loc.getLongitude())
+ "&output=xml&oe=utf8&sensor=true&key=" + GOOGLE_MAPS_API_KEY;
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.connect();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xr = parser.getXMLReader();
GoogleReverseGeocodeXmlHandler handler = new GoogleReverseGeocodeXmlHandler();
xr.setContentHandler(handler);
xr.parse(new InputSource(connection.getInputStream()));
localityName = handler.getLocalityName();
動手看懂 Android 源碼中的策略模式:以 Interpolator 為例
策略模式其實一點都不玄,聽到這裡你可以先鬆口氣。 先用排序理解策略 想像一下排序這件事:官方只對外暴露一個 ISort 接口,裡面有一個 sort() 方法,具體怎麼排
Android 仿斗魚直播彈幕效果完整實作
之前有位朋友在我的公眾號裡問過:像直播那種彈幕功能該如何實現?如今直播產業火熱無比,大大小小的公司都想涉足這個領域,用斗魚的話來說,現在就是「千播之戰」。而彈幕無疑是直播
在 Android 中運用 jxl 組件操作 Excel 文件
1. jxl 支持 Excel 95-2000 的所有版本,能生成 Excel 2000 標準格式,涵蓋字體、數字、日期等操作,還能修飾單元格屬性、支持圖像與圖表。最關鍵
Android ViewStub 用法詳解:需要時才載入的零尺寸佔位元件
ViewStub 的用途是在執行階段才把版面 lazily inflate 進來。官方文件的定義是: A ViewStub is an invisible, zero-s