如何确保getLastLocation().isSuccessful()



我尝试getLastLocation(),但有时是null。当这种情况发生时,我会在谷歌地图上搜索一秒钟,然后返回我的应用程序,99%就可以了。还有一个应用程序只返回你所在的城市,即使我的应用无法getLastLocation(),它也能工作。我注意到,当我使用另一个应用程序、谷歌地图或天气应用程序时,状态栏会短时间显示位置图标,但当我使用我的应用程序时该图标永远不会出现,所以我猜这可能是问题所在?

我需要做些什么来确保我的位置!=无效的

还有一件事,有时我会得到我的位置(lat和long(,但反向地理编码会因为List是空的而被捕获?如何确保它始终不是空的?

我使用的代码只是android开发人员的复制/过去。

如果您使用的是Android Emulator,则除非打开地图应用程序,否则位置不会更新。

为了确保您获得non-null location,您需要request for location updates

你可以做一些类似的事情

@SuppressLint("MissingPermission")
private fun getLastKnownLocation() {
// get last known location from fusedLocationProviderClient returned as a task
fusedLocationProviderClient.lastLocation
.addOnSuccessListener { lastLoc ->
if (lastLoc != null) {
// initialize lastKnownLocation from fusedLocationProviderClient
lastKnownLocation = lastLoc

} else {
// prompt user to turn on location
showLocationSettingDialog()
// when user turns on location trigger updates to get a location
fusedLocationProviderClient.requestLocationUpdates(
locationRequest, locationCallback, Looper.getMainLooper()
)
}
// in case of error Toast the error in a short Toast message
}
.addOnFailureListener {
Toast.makeText(requireActivity(), "${it.message}", Toast.LENGTH_SHORT).show()
}
}

这只是一个存根,您需要处理权限,创建FusedLocationProviderClientLocationRequestLocationCallback对象。

您可能还需要提示用户打开"位置设置">

请向我们展示您的地理编码,以便进一步详细说明。

最新更新