Location Services - unable to initialize onLocationChanged(...) callback


#1

Hey, after much struggle trying to update these tools to the newest available versions, I’m unable to successful initialize the onLocationChange(...) callback. I’m pretty close to tossing out the project and starting this over with whatever documentation is available on Android. Any ideas?

 // building a location request
private void findImage() {
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setNumUpdates(1);
    request.setInterval(0);
    // sending a location request
    // this was recommended for the deprecated FusedLocationAPi
    if (ActivityCompat.checkSelfPermission(getActivity(),
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getContext(),
            android.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;
    }
    LocationServices.FusedLocationApi
            .requestLocationUpdates(mClient, request, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.i(TAG, "Got a fix: " + location);
                    new SearchTask().execute(location);
                }
            });
}

private boolean hasLocationPermission() {
    int result = ContextCompat
            .checkSelfPermission(getActivity(), LOCATION_PERMISSIONS[0]);
    return result == PackageManager.PERMISSION_GRANTED;
}

#2

Alright - I let this sit for a day and I rubber-duckied this problem to a friend. This is something really interesting - change setNumUpdates(1) to setNumUpdates(2).

pg. 634

  • number of updates - how many times the location should be updated

Sadly, Google Location Services API is private, so I cannot verify for sure. The theory my friend has is that it’s possible the LocationServices.FusedLocationApi has changed behavior since the 3rd edition was first printed.

In any case, it appears that the desired behavior is for the callback onLocationChanged(...) to be triggered, you must obtain more than one request for a location. Would be nice to verify, but this is solution, as it appears to work now.