如果有一个 Intent 过滤器,为什么要检查 BroadcastReceiver 中的 Intent 动作

Why check Intent's action in BroadcastReceiver if theres an intent filter in place

我正在查看 Android 蓝牙开发人员文档并查看此处的代码片段,想知道如果您已经过滤了特定的意图操作类型,为什么还需要检查该意图的操作。

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

此处根据给定的示例,它不需要检查操作条件,但如果您对多个操作使用同一个接收器,则需要检查操作,例如,

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, intentFilter);

在这种情况下,您需要检查接收器中的操作,因为我们需要区分我们收到的是哪个广播。

BroadcastReceiver.onReceive()documentation 包含以下警告:

The Intent filters used in registerReceiver(BroadcastReceiver, IntentFilter) and in application manifests are not guaranteed to be exclusive. They are hints to the operating system about how to find suitable recipients. It is possible for senders to force delivery to specific recipients, bypassing filter resolution. For this reason, onReceive() implementations should respond only to known actions, ignoring any unexpected Intents that they may receive.