Execute code on main thread in Android without access to an Activity?

后端 未结 5 1820
一整个雨季
一整个雨季 2020-12-16 10:32

I have an Android service that starts and maintains a background thread.

From time to time, the background thread needs to do a callback on the main thread. I\'m stu

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 11:13

    If you code in Kotlin you can use coroutine with Main dispatcher:

    private fun runOnUiThread(block: () -> Unit) {
        CoroutineScope(Dispatchers.Main).launch { block.invoke() }
    }
    

    Of-cause coroutines should added to your project as a dependency.

提交回复
热议问题