到目前为止,我一直在使用GoogleApiClient
获取当前位置,但我发现使用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) {
}
答案 0 :(得分:2)
使用以下方法获取Location
对象:
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
的更多信息,请refer to the docs。