Android BroadcastReceiver 处理多条消息

Android BroadcastReceiver handling multiple messages

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

假设 BroadcastReceiver 仍在处理 UI 线程上的 message/intent,同时从其他线程触发另一个广播消息 is/are。后面的广播消息会不会放到队列里什么的?

感谢

我想你想要的就在这里: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: 

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.

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

编辑评论
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 更可靠。但也有必要的时候。

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

我将举一个我用于蓝牙连接的示例,展示如何使用 IntentFilter 来获取不同的操作:

IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
getApplication().registerReceiver(mReceiver, filter);

广播接收器:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {     
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {          
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Toast.makeText(getApplicationContext(), "Device not found", Toast.LENGTH_LONG).show();
        }
    }
};

希望对您有所帮助。