如何在Android中不使用getLastKnownLocation方法获取当前纬度和经度?

4
我正在尝试获取手机的 当前 位置,为此我使用了GPSTracker 教程,但问题在于它总是使用方法 getLastKnownLocation 并返回旧的位置。
                if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "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) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }

当使用 NetworkGPS 位置提供者时,您可以查看使用 getLastKnownLocation 的教程,但是我真的需要当前位置。

我不知道如何获取它!

5个回答

6

结合GoogleApiClient使用Fused Location Provider APIs。您可以在此处找到API:https://developer.android.com/reference/com/google/android/gms/location/FusedLocationProviderApi.html。它们旨在提供高精度的位置信息。使用GoogleApiClient来使用它。

new GoogleApiClient.Builder(context)
         .addApi(LocationServices.API)
         .addConnectionCallbacks(this)
         .addOnConnectionFailedListener(this)
         .build()

使用位置提供者还有其他方法。您不应仅限于使用GPS和移动网络获取位置。相反,应该遍历所有位置提供者,并根据精度要求选择给您高精度的提供者。以下代码实现了这一点:

    Location bestResult = null;
    float bestAccuracy = Float.MAX_VALUE;
    long bestAge = Long.MIN_VALUE;
    List<String> matchingProviders = mLocationManager.getAllProviders();

    for (String provider : matchingProviders) {

        Location location = mLocationManager.getLastKnownLocation(provider);

        if (location != null) {

            float accuracy = location.getAccuracy();
            long time = location.getTime();

            if (accuracy < bestAccuracy) {

                bestResult = location;
                bestAccuracy = accuracy;
                bestAge = time;

            }
        }
    }

    // Return best reading or null
    if (bestAccuracy > minAccuracy
            || (System.currentTimeMillis() - bestAge) > maxAge) {
        return null;
    } else {
        return bestResult;
    }

在检查精度后,您可以直接使用位置对象。您应该利用其他应用程序访问的位置,而不仅仅依赖于通过GPS /移动网络获取的位置。

如果您想持续监听位置更新,请实现LocationListener回调以持续获取位置更新。


1
如果我没记错的话,那篇教程相当古老,没有使用融合位置。如果你在Android Studio中开发,请考虑尝试这个库:https://github.com/mcharmas/Android-ReactiveLocation 代码量少得多,使用最新的API进行融合定位。
要获取上次已知的位置,只需:
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
    .subscribe(new Action1<Location>() {
        @Override
        public void call(Location location) {
            // doSthImportantWithObtainedLocation(location);
        }
    });

就是这样!


获取纬度和经度将是 locationProvider.getLatitud 吗? - TuGordoBello
Location对象具有getLatitude()和getLongitude()等方法。http://developer.android.com/reference/android/location/Location.html - cYrixmorten

1
The method mentioned above is the deprecated method and Android has asked developers to use the below method.

https://developer.android.com/training/location/retrieve-current.html

Sample Code


onCreate(){
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            buildAlertMessageNoGps();
        }
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

@Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setInterval(1000 * 60 * 5);

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }
@Override
    public void onLocationChanged(Location location) {

        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            String address = addresses.get(0).getAddressLine(1);

        } catch (IOException e) {
            e.printStackTrace();
        }


        editor.commit();
    }

1
使用以下代码 -
private class LocationListener extends Activity implements android.location.LocationListener{
    Location mLastLocation;
    public LocationListener(String provider){
        Log.e(TAG, "LocationListener " + provider);
        mLastLocation = new Location(provider);
    }


   LocationListener[] mLocationListeners = new LocationListener[] {
        new LocationListener(LocationManager.GPS_PROVIDER),
        new LocationListener(LocationManager.NETWORK_PROVIDER)
   };

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }


    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: " + location);
        mLastLocation.set(location);
        Toast.makeText(mContext, "Driver location :"+location.getLatitude()+" , "+location.getLongitude(), Toast.LENGTH_SHORT).show();
        //TODO call web service to update driver location to server
        driverLocationUpdateServerRequest(location);
    }

    @Override
    public void onProviderDisabled(String provider){
        Log.e(TAG, "onProviderDisabled: " + provider);            
    }

    @Override
    public void onProviderEnabled(String provider){
        Log.e(TAG, "onProviderEnabled: " + provider);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras){
        Log.e(TAG, "onStatusChanged: " + provider);
    }



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initializeLocationManager();
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[1]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "network provider does not exist, " + ex.getMessage());
    }
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[0]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "gps provider does not exist " + ex.getMessage());
    }

 }
} 

1
我认为其中一位回答者使用了locationListner,但这里有一个简单的解决方案,通过调用getBestProvider方法即可返回位置信息,即使GPS不可用。
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 2000, 0, locationListener);

private final LocationListener locationListener = new LocationListener() 
{
  public void onLocationChanged(Location location) 
  {
    Double latitude = location.getLatitude();
    Double longitude = location.getLongitude();
  }

};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接