项目开发要用到GPS的功能,网上找了下资料,整理了下,以便复习。
1 添加权限
<uses-permission android:name="android.permission.ACCESS_FIND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
2 申明
//位置监听对象
locationListener=new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
//位置改变时更新UI
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
updateToNewLocation(location);
}
};
3 打开GPS
/*** 打开GPS
* @return
*/
private boolean openGPSSettings() {
LocationManager alm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
return true;
}
Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
return false;
}
4 获取地理位置
/**
* 获取位置
*/
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);
// 设置监听器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米
locationManager.requestLocationUpdates(provider, 2 * 1000, 500,
locationListener);
}
5 更新位置方法
/**
* 更新地址
* @param location
*/
private void updateToNewLocation(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
tvGps.setText("维度:" + latitude + "\n经度" + longitude);
} else {
tvGps.setText("无法获取地理信息");
}
}