如何在另一种方法中调用onReceive方法?

时间:2015-12-27 23:33:52

标签: java android bluetooth

目前,我开发了一种新方法来发现bluetooh就绪连接。这是我的代码:

private void DiscoverOBDConnection() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mBluetoothAdapter.startDiscovery();
    BroadcastReceiver mReceiver;

    // Create a BroadcastReceiver for ACTION_FOUND
    final List<String> discoverableDevicesList = new ArrayList<String>();

    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);
                short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);

                String discoveredDeviceName = device.getName();
                discoverableDevicesList.add(discoveredDeviceName);
            }
        }
    };

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    context.registerReceiver(mReceiver,filter); // Don't forget to unregister during onDestroy
}

我只是不知道如何从另一种方法调用onreceive方法。你能帮我学习如何实现和发现准备连接的蓝牙设备吗?

1 个答案:

答案 0 :(得分:0)

你可以发送广播

Intent i = new Intent(BluetoothDevice.ACTION_FOUND);
sendBroadcast(i);

或直接致电

mReceiver.onReceive(this, new Intent(BluetoothDevice.ACTION_FOUND));