Android/DalvikVM 如何处理 Handler?

发布于 2024-10-11 00:06:44 字数 1153 浏览 3 评论 0原文

我想知道 Android/DalvikVM 中如何处理处理程序。我正在为 Android 编写一个应用程序,在一个类中我有一个 Handler 方法,它从另一个类接收消息。 Handler 方法会充当线程并与同一类中的 run() 方法异步,还是会等到 run() 方法中的一行代码完成(某种原子操作)?或者其他什么?

我想知道,因为我想在 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() 和处理程序方法中的代码周围有一些同步或信号量或其他东西,这样我就不会损坏我的缓冲区?

I'm wondering how Handlers are processed in Android/DalvikVM. I'm writing an application for Android, and in one class I have a Handler method which receives messages from another class. Will the Handler method act as a Thread and be asynchronous to the run() method in the same class, or will it wait until a line of code in the run() method is finished (sort of atomic operation)? Or something else?

I'm wondering, because I want to add messages to a queue in the Handler method, and process and remove them in the run() method (producer-consumer).

My code structure:

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;
            }
        }
    };
}

When will the code in the handler run? Does it interrupt the code in the run() method at any point? Do I have to have some synchronization or semaphores or something around the code in the run() and handler method so that I don't corrupt my buffer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千鲤 2024-10-18 00:06:44

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

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

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

请注意,在上面的描述中,类根本没有发挥作用,因为类是代码的结构方式,与代码在哪个线程上执行无关。

An Android Handler associates itself with whatever thread it is created in (assuming that thread has a looper already). By default in Android callbacks run on a thread named "main" which is also called the ui thread. Regardless of what thread the post method is called from the handleMessage method will be called from the thread that the Handler was created in (usually the "main" thread). Because the handleMessage method is always called in the same thread, only one message will be processed at a time.

If your plan is to have only a single consumer then Handler is a good choice. You will not need to remove messages from your consumer (the Handler), instead they will simply arrive in handleMessage for processing. If you want to do processing on the "main" thread then you just make a new Handler, if you want to do processing in the background to avoid ANRs you will likely want to use HandlerThread. Here's an example of a Handler running on it's own background thread:

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

Notice that in the description above class does not come into play at all because classes are how code is structured which is unrelated to what thread the code is executed on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文