android - 如何从 Fragment 或 Activity 调用挂起函数?

标签 android kotlin-coroutines

我想请求权限并通过非阻塞函数来完成。因为我需要上下文,所以我不能从 ViewModel 调用它。如何为 fragment 提供默认 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)
    }
 }
}

关于android - 如何从 Fragment 或 Activity 调用挂起函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043638/

相关文章:

android - Kotlin Coroutines - 嵌套协程是在一个协程中处理不同线程的正确方法吗?

kotlin - 改造成功后,协程问题将数据插入房间数据库

kotlin - 如何从非暂停回调函数从LiveData构建器发出

android - Kotlin Coroutines如何实现正确调用api

unit-testing - 如何对具有协程 `GlobalScope.launch` 的函数进行单元测试

安卓通知回调

android - 如何测试android应用程序?

android - 运行应用程序但不从启动器运行

属性 app :itemIconTint will be ignored 的 Android 数据绑定(bind)应用程序命名空间

java - 如何从Sql Server数据库中检索数据?