我想请求权限,并通过非阻塞函数进行。因为我需要上下文,所以不能从ViewModel中调用它。如何为碎片和调用暂停函数指定默认的UI作用域:
class MapsFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
launch {
withContext(Dispatcher.Main){
checkLocationPermission().await()
}
}
}
}
suspend fun checkLocationPermission():Boolean{...}
文档https://developer.android.com/topic/libraries/architecture/coroutines中说我可以使用androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01
ktx。
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
val params = TextViewCompat.getTextMetricsParams(textView)
val precomputedText = withContext(Dispatchers.Default) {
PrecomputedTextCompat.create(longTextContent, params)
}
TextViewCompat.setPrecomputedText(textView, precomputedText)
}
}
}