Android - 获取当前位置无效

时间:2018-06-05 08:50:38

标签: android avd

我遇到了获取LocationManager对象的问题。代码应适用于所有Android API,但在我的测试中,我发现LocationManager仅在25 API中不为空。

   fun invokeLocalization(): Location? {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val locationManager = ctx.applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if ( ctx.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            var bestLocation: Location? = null
            for (provider in locationManager.getProviders(true)) {
                val location = locationManager.getLastKnownLocation(provider) ?: continue
                if (bestLocation == null || location.accuracy < bestLocation.accuracy) bestLocation = location
            }
            return bestLocation
        } else {
            (ctx as AddAlertActivity).requestPermissions(arrayOf(LocationManager.GPS_PROVIDER),PackageManager.PERMISSION_GRANTED)
            return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
        }
    }
    return null
}

我的清单

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.location.gps" />

在Android的设置中启用了预设的本地化。 enter image description here

我将非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

使用谷歌的FusedLocation API获取更新的位置或上次知道的位置

https://developers.google.com/location-context/fused-location-provider/