获取经纬度位置的代码如下:// 获取地理位置管理器
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// 获取所有可用的位置提供器
List providers = locationManager.getProviders(true);
if (providers.contains(LocationManager.GPS_PROVIDER)) {
// 可以用 GPS 获取位置
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location.getLatitude();
location.getLongitude();
}
}
else if(providers.contains(LocationManager.NETWORK_PROVIDER)){
// GPS 不能用,使用网络获取位置
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
location.getLatitude();
location.getLongitude();
}
别忘了权限:
当然,即使我们加了权限,官方还是建议我们在使用位置前,加上权限判断:// 权限检查
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
但是!上面的代码是静态的,也就是说是一次性获取的!但是我们知道 GPS 并不是时时刻刻都准备好的,都是有信号的,所以很有可能会遇到取值失败的情况,所以我们可以优化下:LocationManager locationManager = (LocationManager)m_context.getSystemService(Context.LOCATION_SERVICE);
// 从“位置管理器”获取“驱动器”
List providers = locationManager.getProviders(true);
// “驱动器”中是否包含 GPS,我们这里假设必须用 GPS 定位,没有 GPS 就返回。
if (!providers.contains(LocationManager.GPS_PROVIDER)) {
return;
}
// minTime:多久更新一次,单位毫秒。
// minDistance:与前值差距超过此值时,才通知。
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 1000, 10, m_locationListener);
使用 locationManager.requestLocationUpdates 方法,它每隔指定条件下,就会去调用 m_locationListener,所以通常 m_locationListener 会不断地被调用。
m_locationListener 怎么写呢?示例如下:m_locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
if (location == null) {
return;
}
location.getLatitude()
location.getLongitude()
location.getAccuracy()
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
用完了怎么关闭呢?如下:if (locationManager != null && m_locationListener != null) {
locationManager.removeUpdates(m_locationListener);
}
if (locationManager != null) {
locationManager = null;
}