Running code in main thread from another thread

前端 未结 16 2082
一个人的身影
一个人的身影 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

    I know this is an old question, but I came across a main thread one-liner that I use in both Kotlin and Java. This may not be the best solution for a service, but for calling something that will change the UI inside of a fragment this is extremely simple and obvious.

    Java (8):

     getActivity().runOnUiThread(()->{
          //your main thread code
     });
    

    Kotlin:

    this.runOnUiThread {
         //your main thread code
    }
    

提交回复
热议问题