Reputation: 5460
At the moment when i use the geo fix lng lat command my application doesn't pick up that the location has changed. My simplified code looks like this:
if (googleApiClient.isConnected()) {
Location lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastKnownLocation!= null){
Log.d("Log", "Lat: " + lastKnownLocation.getLatitude());
Log.d("Log", "Lng: " + lastKnownLocation.getLongitude());
} else {
Log.d("Log", "No location detected");
}
}
googleApiClient:
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
So with the activity containing that code running i can send the command "geo fix 10 10" and reload that code (via a refresh button) but it will still log "No location Detected"
However, if I open the Google maps application within the emulator and then go back to my application and hit refresh again it will output: "Lat: 10" "lng: 10"
It appears that opening the map application is triggering some sort of update of the apps location that geo fix doesn't?
Thanks
Upvotes: 1
Views: 2857
Reputation: 5460
So after doing a bit of digging through the docs and other questions on here I found that I wasn't actually updating the location at all within the app. (Which was what Google Maps did when I opened it and hence triggered the new location to be set)
It now works (when the app is in the foreground) with this implementation:
protected GoogleApiClient googleApiClient;
protected LocationRequest locationRequest;
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
And then within the overridden onConnected method:
@Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest, this);
}
Plus the onLocationChanged method is required as the class is now implementing LocationListener
@Override
public void onLocationChanged(Location location) {
//Whatever is required when the location changes
}
Upvotes: 3