我是android的绝对初学者。目前,我正在尝试制作一个通过蓝牙将输出数据发送到arduino的应用程序。为此,我创建了一个如下的类。

private class SendReceiveBytes implements Runnable {
    private BluetoothSocket btSocket;
    private InputStream inputStream;
    private OutputStream outputStream;
    String TAG = "SendReceiveBytes";

    public SendReceiveBytes(BluetoothSocket socket) {
        btSocket = socket;
        try {
            inputStream = btSocket.getInputStream();
            outputStream = btSocket.getOutputStream();
        }
        catch (IOException streamError) {
            Log.e(TAG, "Error when getting input or output Stream");
        }
    }

    @Override
    public void run() {
        // buffer store for the stream.
        byte[] buffer = new byte[1024];
        // bytes returned from the stream.
        int bytes;

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = inputStream.read(buffer);
                // Send the obtained bytes to the UI activity
                socketHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            }
            catch (IOException e) {
                Log.e(TAG, "Error reading from inputStream");
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String outputData) {
        try {
            outputStream.write(outputData.getBytes(Charset.forName("UTF-8")));
        }
        catch (IOException e) {
            Log.e(TAG, "Error when writing to outputStream");
        }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            btSocket.close();
        }
        catch (IOException e) {
            Log.e(TAG, "Error when closing the btSocket");
        }
    }
}


在我的OnCreate()方法中,我正在执行以下操作。

final SendReceiveBytes sendBytes = new SendReceiveBytes(bluetoothSocket);
final Handler moveHandler = new Handler();
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            switch (view.getId()) {
                case R.id.driveFwd:
                    moveHandler.postDelayed(sendBytes.write("MOVE_FORWARD"), 250);
                    sendBytes.write("MOVE_FORWARD");
                    break;


我目前遇到的问题是调用方法write()的正确过程。继续进行下去的正确方法是什么?

最佳答案

看一下连接到arduino的此类。我前一段时间写的。问题是,如果您不知道android从这里开始是非常困难的。
看一下BluetoothHandlerClass

https://github.com/rush2sk8/BluetoothHandler

09-11 18:11
查看更多