lastKnownLocation总是返回null在GPS关闭 [英] lastKnownLocation is always returning null when gps is off

查看:482
本文介绍了lastKnownLocation总是返回null在GPS关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用谷歌服务API,LocationServices.FusedLocationApi找到用户的当前,然后更新位置。我在模拟器和实际设备测试,我发现,如果我关掉GPS LocationServices.FusedLocationApi.getLastLocation()始终返回null,但我得到一个有效的值,如果我打开GPS。这里是code,我现在用的:

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.

推荐答案

我觉得你应该检查一下你的设备具有GPS首次使用这样的:

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

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

有关详细信息和code请参照<一个href=\"https://github.com/jbj88817/getLastLocationUsingGPS-android/blob/master/app/src/main/java/com/bojie/locationex/MapsActivity.java\"相对=nofollow>这里。

For more info and code please refer here.

这篇关于lastKnownLocation总是返回null在GPS关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆