I have been trying to get location (lat/lon) using Fused Location Api in andriod. My code works fine when both wifi and gps are on. If I turn off the gps then i don't get any location update.
I am using BALANCED_POWER_ACCURACY for location request.
I have added Access_FINE_Location permission in manifest and using play services version 9.2.1 in my build.gradle file.
I am testing on real devices(Samsung SM0G360H API 19 and Samsung SM-G361 API 21). Both give the same results.
Can anyone tell me how exactly Fused Location Api works?
How can i get location updates while gps is off but network connection is on?
My code:
public class LocationUpdateusingFused extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener{
TextView txtOutputLat, txtOutputLon;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;
Intent batteryStatus;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fleet_layout);
txtOutputLat = (TextView) findViewById(R.id.textView);
txtOutputLon = (TextView) findViewById(R.id.textView2);
buildGoogleApiClient();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setMaxWaitTime(5000);
mLocationRequest.setInterval(10000); // Update location every second
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
}
catch (SecurityException e)
{
Log.e("LocatonUpdate",e+" ");
}
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());
}
updateUI();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
Log.e("LocationChanged",location.getSpeed()+" "+location.getAccuracy()+" "+location.getBearing()+" "+location.getProvider()+" "+location.getAltitude()
);
updateUI();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
void updateUI() {
txtOutputLat.setText(lat);
txtOutputLon.setText(lon);
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}