我想在 Android Kotlin 应用程序显示的 Google 地图上设置一个标记,作为我选择的 URL。很明显,获取 URL 内容需要在 UI 线程之外完成,而协程是这里的方法,所以我想运行几行代码来获取 URL 并将其放入BitmapDescription
协程内的对象中,然后使用它BitmapDescription
来调用对象setIcon
以Marker
设置自定义图像。
我已经有一个Marker
, 和一个 URL。所以我尝试了这个:
uiScope.launch(Dispatchers.IO) { // not sure this is the best way to launch in IO
val furl = URL(myURL)
val bm = BitmapFactory.decodeStream(furl.openConnection().getInputStream())
val bd = BitmapDescriptorFactory.fromBitmap(bm)
uiScope.launch(Dispatchers.Main) { // go back to UI thread; this crashes
marker.setIcon(bd)
}
}
这显然是不对的,因为它会崩溃。据我所知,获取 URL 并创建一个BitmapDescriptor
似乎工作正常;一旦我有了它BitmapDescriptor
,我该如何打电话marker.setIcon
?