以编程方式从广播接收器连接Android中的蓝牙设备

时间:2015-03-02 03:00:41

标签: java android android-studio bluetooth broadcastreceiver

在我的广播接收器中,我检索了一个绑定的蓝牙设备列表。

BluetoothStateChangedReceiver extends BroadcastReceiver

这就是我获得配对设备的方式:

private void getPairedDevices(){
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices == null || pairedDevices.size() == 0) {
        showToast("No Paired Devices Found");
    } else {
        ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
        list.addAll(pairedDevices);
        mPairedDeviceList = list;
    }
}

我叫这段代码:

BluetoothDevice device = mPairedDeviceList.get(0);
            deviceName = device.getName();

            if(device.getBondState()==device.BOND_BONDED){
                Log.d(TAG,"Device Name"+device.getName());
                BluetoothSocket mSocket= null;
                try {
                    mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e1) {
                    Log.d(TAG,"socket not created");
                    e1.printStackTrace();
                }
                try{
                    mSocket.connect();
                }
                catch(IOException e) {
                    try {
                        mSocket.close();
                        Log.d(TAG, "Cannot connect");
                    } catch (IOException e1) {
                        Log.d(TAG, "Socket not closed");
                        e1.printStackTrace();
                    }

                }

            }

我的UUID是

private static final UUID MY_UUID = UUID.fromString("DEADBEEF-0000-0000-0000-000000000000");

但是,我从来没有能够连接到设备?

我打开蓝牙后,我只是尝试以编程方式连接到蓝牙音箱。我错过了什么?

1 个答案:

答案 0 :(得分:1)

createInsecureRfcommSocketToServiceRecord方法在Android 2.1和2.2上存在一些问题。以下代码在catch部分中说明了这些设备:

try {
        mBtSocket = btDevice
                .createRfcommSocketToServiceRecord(BT_SRVC_UUID);
        mBtSocket.connect(); 
    } catch (Exception e) {
        Log.e(TAG, "createInsecureRfcommSocket", e);
        Log.d(TAG, "trying with reflection");

        BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter()
                .getRemoteDevice(btDevice.getAddress());
        Method m;
        m = hxm.getClass().getMethod("createRfcommSocket",
                new Class[] { int.class });
        mBtSocket = (BluetoothSocket) m.invoke(hxm, Integer.valueOf(1));
        mBtSocket.connect();
    }

要获取btDevice和BT_SRVC_UUID,我使用以下代码:

BluetoothDevice btDevice = BluetoothAdapter.getDefaultAdapter()
            .getRemoteDevice(macBtAddress);

Finallly您应始终确保设备无法正常运行 调用connect()时的设备发现。

mBluetoothAdapter.cancelDiscovery();

要获取设备的macBTAddress,您可以使用bluetoothAdapter搜索设备并获取以前配对设备的mac地址。将来mac地址不会改变,所以你可以保存它。

BT_SRV_UUID是您服务的ID。您可以选择您喜欢的UUID,只需确保它具有有效的语法(您可以使用我的代码中建议的那个)。