Running code in main thread from another thread

前端 未结 16 2079
一个人的身影
一个人的身影 2020-11-22 13:50

In an android service I have created thread(s) for doing some background task.

I have a situation where a thread needs to post certain task on main thread\'s message

16条回答
  •  迷失自我
    2020-11-22 14:18

    Kotlin versions

    When you are on an activity, then use

    runOnUiThread {
        //code that runs in main
    }
    

    When you have activity context, mContext then use

    mContext.runOnUiThread {
        //code that runs in main
    }
    

    When you are in somewhere where no context available, then use

    Handler(Looper.getMainLooper()).post {  
        //code that runs in main
    }
    

提交回复
热议问题