Running code in main thread from another thread

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

    So most handy is to do sort of:

    import android.os.AsyncTask
    import android.os.Handler
    import android.os.Looper
    
    object Dispatch {
        fun asyncOnBackground(call: ()->Unit) {
            AsyncTask.execute {
                call()
            }
        }
    
        fun asyncOnMain(call: ()->Unit) {
            Handler(Looper.getMainLooper()).post {
                call()
            }
        }
    }
    

    And after:

    Dispatch.asyncOnBackground {
        val value = ...// super processing
        Dispatch.asyncOnMain { completion(value)}
    }
    

提交回复
热议问题