gpt4 book ai didi

Android BroadcastReceiver 处理多条消息

转载 作者:行者123 更新时间:2023-11-29 20:31:16 28 4
gpt4 key购买 nike

我想知道 BroadcastReceivers 如何处理多个消息请求(广播 Intent )。

假设 BroadcastReceiver 仍在处理 UI 线程上的消息/Intent ,同时从其他线程触发另一个广播消息。后续的广播消息会不会放入队列之类的?

谢谢

最佳答案

我想你想要的是这里:http://codetheory.in/android-broadcast-receivers/

Asynchronous Processing

Generally after the execution of onReceive() of the receiver class is finished, the Android system is allowed to recycle the receiver, i.e., another intent can be passed to it. For potentially long running operations it is recommended to trigger a service instead on the context object passed to it. This is a reason why any asynchronous operation wasn’t allowed to perform till API level 11. But that has changed now.

Since API 11, if you want to pass on the processing of some task in another thread you could do something like this:

// Sample code from: http://stackoverflow.com/a/22741384

final PendingResult result = goAsync();
Thread thread = new Thread() {
public void run() {
int i;
// Do processing
result.setResultCode(i);
result.finish();
}
};
thread.start();

Using goAsync() we returned an object of the type PendingResult on which calling the finish() method indicates the Android system that the receiver is no more alive and can be recycled.

他在这里说的是,你的接收器在完成执行后被回收,这意味着你一次可以接收一个,但你可以接收很多。

编辑评论
Android 框架工程师 Dianne Hackborn (https://groups.google.com/forum/#!topic/android-developers/ClIGNuGJUts) 发表的声明略微纠正了我的观点:

A particular receiver can only process one broadcast at a time. As each broadcast happens, it is processed to determine the targets it should go to, and dispatched into the message queue for each target.

看来它确实为您创建了一个队列。老实说,我不建议过分依赖广播,在最好的情况下它们很棘手,而且我发现 Message Handlers FAR 更可靠。但有时它们是必要的。

我认为这里最好的选择是实际去尝试并亲眼看看会发生什么。

关于Android BroadcastReceiver 处理多条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31917553/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com