2011-01-10 79 views
2

我想知道处理程序是如何在Android/DalvikVM中处理的。我正在为Android编写一个应用程序,并且在一个类中我有一个Handler方法,它接收来自另一个类的消息。 Handler方法是作为一个线程运行,并且与同一个类中的run()方法是异步的,还是等待run()方法中的一行代码完成(原子操作)?或者是其他东西?Android/DalvikVM进程处理程序如何?

我想知道,因为我想在Handler方法中将消息添加到队列中,并在run()方法(生产者 - 消费者)中处理并删除它们。

我的代码结构:

public class Parser implements Runnable { 
    public void run() { 
      while(true) { 
      // Remove a byte from the ring buffer and parse it 
      byte b = Ringbuffer_read(); 
      // Parse 
     try { 
       Thread.sleep(40); 
      } catch (InterruptedException e) {} 
      } 
    } 

    private final Handler mHandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      switch (msg.what) { 
      case MESSAGE_READ: 
       // Store all the received bytes in the ring buffer 
       for (int i = 0; i < msg.arg1; i++) { 
        Ringbuffer_store(((byte[]) msg.obj)[i]); 
       } 
       break; 
      } 
     } 
    }; 
} 

时候会在处理程序的代码运行吗?它在任何时候都会中断run()方法中的代码吗?我是否必须在run()和handler方法中有一些同步或信号量或代码,以便我不会损坏缓冲区?

回答

4

Android Handler将自己与创建的任何线程关联(假设线程已经有活套)。默认情况下,Android回调会在名为“main”的线程上运行,该线程也称为ui线程。无论从handleMessage方法中调用post方法的哪个线程都将从处理程序创建的线程(通常是“主”线程)中调用。由于handleMessage方法总是在同一个线程中调用,因此一次只能处理一条消息。

如果您的计划是只有一个消费者,那么Handler是一个不错的选择。您不需要从您的消费者(处理程序)中删除消息,而是只需到达handleMessage进行处理。如果要在“主”线程上执行处理,则只需创建一个新的处理程序,如果要在后台执行处理以避免ANR,则可能需要使用HandlerThread。这里有它自己的后台线程运行的处理程序的一个例子:

HandlerThread handlerThread = new HandlerThread("Consumer"); 
handlerThread.start(); 
Handler consumer = new Handler(handlerThread.getLooper()) { 
    public void handleMessage (Message msg) { 
    } 
}; 

请注意,在上面的类的描述不发挥作用,因为在所有类代码是如何组织是无关的代码是什么线程执行。