Running code in main thread from another thread

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

    One method I can think of is this:

    1) Let the UI bind to the service.
    2) Expose a method like the one below by the Binder that registers your Handler:

    public void registerHandler(Handler handler) {
        mHandler = handler;
    }
    

    3) In the UI thread, call the above method after binding to the service:

    mBinder.registerHandler(new Handler());
    

    4) Use the handler in the Service's thread to post your task:

    mHandler.post(runnable);
    

提交回复
热议问题