无法将BluetoothSocket连接到Arduino

时间:2014-07-19 15:32:07

标签: java android bluetooth arduino rfduino

我目前正在尝试通过蓝牙从我的RFduino(某种类型的arduino)发送我的Android智能手机(版本4.4.4)上的数据。因此我做了一个小的Android应用程序。 现在一切正常,直到我尝试connect我的BluetoothSocket。首先,我得到了IOException: read failed -1,我试图解决这个问题:

IOException: read failed, socket might closed - Bluetooth on Android 4.3

哪个有效。但现在我的应用程序在我致电connect()后冻结了。我知道这是因为该方法阻塞,直到找到连接,但为什么这不连接? 我的RFduino使用BluetoothBLE(低能耗):我是否必须使用BluetoothGatt类作为对应部分? 这是我的代码:

public BluetoothConnection(Activity parentActivity) {
        this.mActivity = parentActivity;
        findBluetooth();
        openBluetooth();
    }

    private void findBluetooth() {
        this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (this.mBluetoothAdapter == null) {

        }

        if (!this.mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            this.mActivity.startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = this.mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if (device.getName().equals("RFduino")) {
                    this.mBluetoothDevice = device;
                    break;
                }
            }
        }
    }

    private void openBluetooth() {
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        try {
            BluetoothSocket tmp = this.mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);
            this.mBluetoothSocket = new NativeBluetoothSocket(tmp);
            this.mBluetoothSocket.connect();
        } catch (IOException e) {
            // try the fallback
            Log.w("BT", "Had to use fallback method!");
            try {
                this.mBluetoothSocket = new FallbackBluetoothSocket(this.mBluetoothSocket.getUnderlyingSocket());
                Thread.sleep(500);
                this.mBluetoothSocket.connect();
            } catch (FallbackException e1) {
                Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
            } catch (InterruptedException e1) {
                Log.w("BT", e1.getMessage(), e1);
            } catch (IOException e1) {
                Log.w("BT", "Fallback failed. Cancelling.", e1);
            }
        }

        try {
            this.mInputStream = this.mBluetoothSocket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

虽然我在上面发布的帖子中描述了NativeBluetoothAdapterFallbackBluetoothAdapter。 感谢您的任何建议。

0 个答案:

没有答案