Running code in main thread from another thread

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

    If you run code in a thread, e.g. do delaying some action, then you need to invoke runOnUiThread from the context. For example, if your code is inside MainActivity class then use this:

    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            myAction();
        }
    });
    

    If your method can be invoked either from main (UI thread) or from other threads you need a check like:

    public void myMethod() {
       if( Looper.myLooper() == Looper.getMainLooper() ) {
           myAction();
       }
       else {
    
    }
    

提交回复
热议问题