kotlin Jetpack中的谷歌Map组合冻结

jk9hmnmh  于 2023-02-13  发布在  Kotlin
关注(0)|答案(1)|浏览(131)

当在onInfoWindowClick中触发导航时,我的应用程序会冻结。在我构建的这一点上,我已经导航到不同的可组合对象无数次了,所以这段代码应该可以工作。

GoogleMap(
               modifier = Modifier.fillMaxSize(),
               cameraPositionState = cameraPositionState,
               properties = mapProperties
           ) {
               testData.forEach { contact ->

                   var latlngFinal = LatLng(0.0, 0.0)
                   val coder = Geocoder(LocalContext.current)
                   try {
                       val addresses: ArrayList<Address> = coder.getFromLocationName(contact.address, 50) as ArrayList<Address>
                       for (add in addresses) {
                           latlngFinal = LatLng(add.latitude, add.longitude)
                       }
                   } catch (e: IOException) {
                       e.printStackTrace()
                   }

                   val markerState = rememberMarkerState(null, latlngFinal)

                   Marker(
                       state = markerState,
                       title = contact.title,
                       snippet = contact.description,
                       onInfoWindowClick = {
                           navController?.currentBackStackEntry?.arguments?.putSerializable(
                               "contact_object",
                               userJson
                           )
                           navController?.navigate(route = Routes.RecruitersInAreaDetail.route)
                       }
                   )
                   builder.include(latlngFinal)

               }

               cameraPositionState.move(CameraUpdateFactory.newLatLngBounds(builder.build(), 64))

           }
ybzsozfc

ybzsozfc1#

您的应用冻结,因为您正在从UI线程的foreach循环内调用coder.getFromLocationName。根据文档,此调用将阻止您的UI线程:
从位置获取(双精度浮点数,%20双精度浮点数,%20整数)
你应该把coder.getFromLocationName这个移到你的视图模型里面,如下所示:

viewModelScope.launch(Dispatchers.IO) {
        try {
            val addresses: ArrayList<Address> = coder.getFromLocationName(contact.address, 50) as ArrayList<Address>
        } catch (exception: IOException) {
            Log.i("RegistrationScreen", "setAddress IOException")
        }
    }

相关问题