lastKnownLocation is always returning null when gps is off

喜夏-厌秋 提交于 2019-12-22 12:19:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!