Add this code to your onConnected, thats where it would get Last Known Location.
private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
private static Context context;
// added
private LocationRequest mLocationRequest;
private Double latitude;
private Double longitude;
private String TAG = ""; // set your TAG
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation == null){
startLocationUpdates();
}
if (mLastLocation != null) {
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
// set your tag
Log.d(TAG, String.valueOf(latitude));
Log.d(TAG, String.valueOf(longitude));
} else {
Toast.makeText(context, "Location not Detected, Did you turn off your location?", Toast.LENGTH_SHORT).show();
}
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(30 * 1000)
.setFastestInterval(5 * 1000);
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
And remove synchronized from your method, Just make it public. Something like this below:
public void buildGoogleApiClient() { }
solved Fused Location always returns null