android 擷取GPS定位,

來源:互聯網
上載者:User

/**
* 得到位置資訊
*/
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許可權,否則會出錯。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.