Android消息"什么"代码在处理程序或线程范围内需要是唯一的?

CCJ*_*CCJ 5 java multithreading android

消息'what'字段对于Handler实例或一个或多个Handler实例可能与之关联的线程的MessageQueue是唯一的吗?该文档阅读"A处理器让您发送和处理信息和Runnable对象与线程的MessageQueue关联.每个处理程序实例与单个线程关联和线程的消息队列.当你创建一个新的处理程序,它被绑定到线程正在创建它的线程的/ message队列 - 从那时起,它将消息和runnables传递给该消息队列并在它们从消息队列中出来时执行它们"这似乎表明消息'什么'代码必须对于MessageQueue是唯一的,因此在单个线程的范围内而不是Handler的单个实例.

我的整个项目中有几个与我的UI线程相关联的Handler对象,所以我必须确保发送到这些处理程序中的所有Message"what"代码都是唯一的,或者它们只需要对每个Handler实例都是唯一的?

例如,在执行以下代码并收到两条消息后,日志会说什么:

class MainActivity extends Activity{
  public static final String TAG = "MainActivity";
  public static final int FIRST_PURPOSE_MESSAGE_CODE = 1;
  public static final int SECOND_PURPOSE_MESSAGE_CODE = 1;
  ...
  private static class FirstUIThreadHandler extends Handler{
    ...
    @Override
    public void handleMessage(Message msg){
      switch(msg.what){
        case FIRST_PURPOSE_MESSAGE_CODE:
          Log.v(TAG,"handling the first message");
          break;
      }
    }
  }
  ...
  private static class SecondUIThreadHandler extends Handler{
    ...
    @Override
    public void handleMessage(Message msg){
      switch(msg.what){
        case SECOND_PURPOSE_MESSAGE_CODE:
          Log.v(TAG,"handling the second message");
          break;
      }
    }
  }

  ...
  FirstUIThreadHandler firstUIThreadHandler = new FirstUIThreadHandler(...);
  SecondUIThreadHandler secondUIThreadHandler = new SecondUIThreadHandler(...);
  Message firstMsg = firstUIThreadHandler.obtainMessage();
  firstMsg.what = FIRST_PURPOSE_MESSAGE_CODE;
  firstUIThreadHandler.sendMessage(firstMsg);
  Message secondMsg = secondUIThreadHandler.obtainMessage();
  secondMsg.what = SECOND_PURPOSE_MESSAGE_CODE;
  secondUIThreadHandler.sendMessage(secondMsg);
  ...

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*res 3

消息将仅传递到您用来发送消息的处理程序,两个不同的处理程序不会共享有关发送到不同处理程序的消息的任何信息,因此,如果您在不同的消息中具有相同的“what”属性,它将传递给调用“sendMessage(yourMessage)”的处理程序的“handleMessage(Message msg)”,例如:

secondUIThreadHandler.sendMessage(secondMsg);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,这意味着该消息将仅由第二个处理程序接收,并且无论该属性是否与第二个 UIThreadHandler 中使用的当前消息之外的另一个消息相同,它都能够使用“what”属性。

希望能帮助到你!

问候!