/**
* 得到位置資訊
*/
private void getLocation() {
// 擷取位置管理服務
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(serviceName);
// 尋找到服務資訊
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true); // 擷取GPS資訊
Location location = locationManager.getLastKnownLocation(provider); // 通過GPS擷取位置
updateToNewLocation(location);
try {
tv1.setText(getLocation(location));
} catch (Exception e) {
e.printStackTrace();
Log.e("", e.getMessage());
}
}
/**
* 根據精度和緯度定位到城市
*
* @param itude
* @return
* @throws Exception
*/
private String getLocation(Location itude) throws Exception {
String resultString = "";
/** 這裡採用get方法,直接將參數加到URL上 */
String urlString = String.format(
"http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s",
itude.getLatitude(), itude.getLongitude());
Log.i("URL", urlString);
/** 建立HttpClient */
HttpClient client = new DefaultHttpClient();
/** 採用GET方法 */
HttpGet get = new HttpGet(urlString);
try {
/** 發起GET請求並獲得返回資料 */
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
BufferedReader buffReader = new BufferedReader(
new InputStreamReader(entity.getContent()));
StringBuffer strBuff = new StringBuffer();
String result = null;
while ((result = buffReader.readLine()) != null) {
strBuff.append(result);
}
resultString = strBuff.toString();
/** 解析JSON資料,獲得物理地址 */
if (resultString != null && resultString.length() > 0) {
JSONObject jsonobject = new JSONObject(resultString);
JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
.toString());
resultString = "";
for (int i = 0; i < jsonArray.length(); i++) {
resultString = jsonArray.getJSONObject(i).getString(
"address");
}
}
} catch (Exception e) {
throw new Exception("擷取物理位置出現錯誤:" + e.getMessage());
} finally {
get.abort();
client = null;
}
return resultString;
}
補充一下:
在AndroidMenifest.xml裡面需要加上
android.permission.INTERNET、android.permission.ACCESS_COARSE_LOCATION、android.permission.READ_PHONE_STATE許可權,否則會出錯。