Android 如何使用LocationManager获取初始位置?
到目前为止,我一直在使用Android 如何使用LocationManager获取初始位置?,android,locationmanager,Android,Locationmanager,到目前为止,我一直在使用GoogleAppClient获取当前位置,但我刚刚注意到,使用LocationManager使用LocationListener来获取当前位置要简单得多,因为它甚至可以检测用户何时打开或关闭GPS服务 但是在初始化LocationManager之后获取用户的第一个位置时,我遇到了一个问题 LocationManager有4个侦听器,但没有一个能为您提供第一个位置。它确实有一个onLocationChanged侦听器,但它仅在您移动时激活 我就是这样使用它的: // In
GoogleAppClient
获取当前位置,但我刚刚注意到,使用LocationManager
使用LocationListener
来获取当前位置要简单得多,因为它甚至可以检测用户何时打开或关闭GPS服务
但是在初始化LocationManager
之后获取用户的第一个位置时,我遇到了一个问题
LocationManager
有4个侦听器,但没有一个能为您提供第一个位置。它确实有一个onLocationChanged
侦听器,但它仅在您移动时激活
我就是这样使用它的:
// Init LocationManager (needed to track if GPS is turned on or not
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
end of oncreate......
/*
LocationListener (Listening if GPS service is turned on/off)
*/
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderDisabled(String provider) {
}
使用以下方法获取
位置
对象:
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v(TAG, "isGPSEnabled =" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v(TAG, "isNetworkEnabled =" + isNetworkEnabled);
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled && location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
} catch (Exception e) {
Log.e(TAG, "Location Not Found");
}
return location;
}
有关方法
getLastKnownLocation
的详细信息,请。否,切勿使用此代码。它有很多错误,包括它不总是使用GPS,可能返回陈旧数据或空值,而且它不总是有位置,即使它说它有。请参阅全文up@GabeSechan,您的链接已关闭,您可以更新它或以某种方式发送代码吗?我很好奇为什么这个代码如此糟糕。