android 获取GPS定位,

来源:互联网 发布:天猫魔盒直播软件 编辑:程序博客网 时间:2024/04/30 12:36
/**
* 得到位置信息
*/
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权限,否则会出错。

原创粉丝点击