问题
I am using Google Service API , LocationServices.FusedLocationApi to find user's current and then updated Location. I have tested on emulator as well as on actual device and I have found that if I turn off GPS LocationServices.FusedLocationApi.getLastLocation() always returns null, however I get a valid value if I turn on the GPS. Here is the code which I am using:
private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
mLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastKnownLocation != null) {
Log.i(TAG, String.valueOf(mLastKnownLocation.getLatitude()));
Log.i(TAG, String.valueOf(mLastKnownLocation.getLongitude()));
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), this);
Am I missing something here? Thanks in advance.
回答1:
I think u should check if the your device has a GPS first by using this:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
And then use the LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
.
For more info and code please refer here.
来源:https://stackoverflow.com/questions/33121177/lastknownlocation-is-always-returning-null-when-gps-is-off