【问题标题】:lastKnownLocation is always returning null when gps is off当 gps 关闭时,lastKnownLocation 始终返回 null
【发布时间】:2015-10-14 09:11:20
【问题描述】:

我正在使用 Google 服务 API、LocationServices.FusedLocationApi 来查找用户的当前位置,然后再更新位置。我已经在模拟器和实际设备上进行了测试,我发现如果我关闭 GPS LocationServices.FusedLocationApi.getLastLocation() 总是返回 null,但是如果我打开 GPS,我会得到一个有效值。这是我正在使用的代码:

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);

我在这里遗漏了什么吗? 提前致谢。

【问题讨论】:

    标签: android android-emulator gps google-play-services location-services


    【解决方案1】:

    我认为你应该先检查你的设备是否有 GPS:

    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();
        }
    

    然后使用LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)

    更多信息和代码请参考here

    【讨论】:

    • @bijang 感谢您的回答和详细的代码。我试图了解如果 GPS 被禁用,那么会发生什么?目前如果 GPS 被禁用,那么它不会显示我的位置,我该如何解决这个问题?
    • 获取当前位置的两种方法: 1. 从GPS,您需要拥有GPS 并启用它。 2. 来自Network Location Provider,但这不是GPS的准确度。更多详情请参考here
    • 我遇到了问题,我的印象是即使位置功能被禁用,网络位置提供程序也能正常工作。但事实并非如此。如果我必须找到位置(不同的位置模式),则必须启用位置。感谢您的帮助
    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2016-05-31
    • 2015-08-15
    • 2012-03-18
    • 2016-11-04
    相关资源
    最近更新 更多