首页 > 解决方案 > 重新启用定位服务

问题描述

在我禁用手机上的位置服务然后启用它们后,getLastKnownLocation()尽管它使用的提供程序已启用,但它们返回 null。有谁知道如何解决这个问题?

另外,如果我打开谷歌地图应用程序然后返回我的应用程序,它似乎可以解决问题。

代码:

private Location getLastKnownLocation() {
    LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            boolean enabled = mLocationManager.isProviderEnabled(provider);
            @SuppressLint("MissingPermission")
            Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                Log.d("DebuggingLocation", "Skipped " + provider + " " + String.valueOf(enabled));
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                bestLocation = l;
            }
        }
        return bestLocation;
    }

日志:

D/DebuggingLocation: Skipped passive true
D/DebuggingLocation: Skipped gps true
D/DebuggingLocation: Skipped network true

标签: android

解决方案


通过请求被动、gps 和网络提供商的位置更新解决了问题。


推荐阅读