在android中一般是子线程向主线程发送消息,那主线程能否向子线程发送消息呢?答案是肯定的。

请看android文档中Looper类的一段文档:

Classusedtorunamessageloopforathread.Threadsbydefaultdonothaveamessageloopassociatedwiththem;tocreateone,callprepare()inthethreadthatistoruntheloop,andthenloop()tohaveitprocessmessagesuntiltheloopisstopped.

MostinteractionwithamessageloopisthroughtheHandlerclass.

ThisisatypicalexampleoftheimplementationofaLooperthread,usingtheseparationofprepare()andloop()tocreateaninitialHandlertocommunicatewiththeLooper.

class LooperThread extends Thread {
      public Handler mHandler;
      
      public void run() {
          Looper.prepare();
          
          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };
          
          Looper.loop();
      }
  }

主线程通过子线程中定义的Handler向子线程发送message。先写到这里吧,等周末有空再进行详细说明。