Java 如何读取通过蓝牙发送的反输入值?

Java 如何读取通过蓝牙发送的反输入值?,java,android,bluetooth,arduino,serial-communication,Java,Android,Bluetooth,Arduino,Serial Communication,我想使用从Arduino发送到android的数据。我能够将两者连接在一起,并在屏幕上显示输入的数据。然而,当我想使用传入数据来设置注释时,这似乎不起作用。那么,如何从传入的数据中获取值呢 String address1 = ("98:D3:81:FD:4B:87"); String name1 = ("Sensor_Shoe"); @SuppressLint("HandlerLeak") protected void bluetoothconnect() {

我想使用从Arduino发送到android的数据。我能够将两者连接在一起,并在屏幕上显示输入的数据。然而,当我想使用传入数据来设置注释时,这似乎不起作用。那么,如何从传入的数据中获取值呢

    String address1 = ("98:D3:81:FD:4B:87");
    String name1 = ("Sensor_Shoe");

    @SuppressLint("HandlerLeak")
    protected void bluetoothconnect() {
        btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        requestCodeForEnable=1;
        if (myBluetoothAdapter==null){
            Toast.makeText(getApplicationContext(),"Bluetooth not supported", Toast.LENGTH_LONG).show();
        } else {
            if (!myBluetoothAdapter.isEnabled()) {
                startActivityForResult(btEnablingIntent, requestCodeForEnable);
            }
            if (myBluetoothAdapter.isEnabled()) {
                myBluetoothAdapter.disable();
                Toast.makeText(getApplicationContext(),"Bluetooth disabled",Toast.LENGTH_SHORT).show();
                TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.INVISIBLE);
                ImageButton btn_bluetooth = findViewById(R.id.btn_bluetooth); btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==requestCodeForEnable){
            ImageButton btn_bluetooth = findViewById(R.id.btn_bluetooth);
            if(resultCode==RESULT_OK){
                Toast.makeText(getApplicationContext(),"Bluetooth enabled",Toast.LENGTH_SHORT).show();
                TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.VISIBLE);
                btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                createsocket();
            }
            else if(resultCode==RESULT_CANCELED){
                Toast.makeText(getApplicationContext(),"Bluetooth enabling cancelled",Toast.LENGTH_SHORT).show();
                TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.INVISIBLE);
                btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
        }
    }

    protected void createsocket() {
        new Thread() {
            public void run() {
                boolean fail = false;

                BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address1);

                try {
                    BTSocket = createBluetoothSocket(device);
                } catch (IOException e) {
                    fail = true;
                    Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                }
                // Establish the Bluetooth socket connection.
                try {
                    BTSocket.connect();
                } catch (IOException e) {
                    try {
                        fail = true;
                        BTSocket.close();
                        BTHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
                                .sendToTarget();
                    } catch (IOException e2) {
                        //insert code to deal with this
                        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                    }
                }
                if (!fail) {
                    mConnectedThread = new ConnectedThread(BTSocket);
                    mConnectedThread.start();
                    BTHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name1)
                            .sendToTarget();
                }
            }
        }.start();
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        try {
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
            return (BluetoothSocket) m.invoke(device, PORT_UUID);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
        return  device.createRfcommSocketToServiceRecord(PORT_UUID);
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
            } catch (IOException e) { }
            mmInStream = tmpIn;
        }

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.available();
                    if(bytes != 0) {
                        buffer = new byte[1024];
                        SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
                        bytes = mmInStream.available(); // how many bytes are ready to be read?
                        bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
                        BTHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                                .sendToTarget(); // Send the obtained bytes to the UI activity
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
这就是我连接的方式,这似乎工作正常。然后我用Neith下的代码读取输入数据

BTHandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg.what == MESSAGE_READ) {
                    String readMessage = " ";
                    try {
                        readMessage = new String((byte[]) msg.obj, "UTF-8");
                        inputdata1 = readMessage;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    TextView input1 = findViewById(R.id.input1);
                    input1.setText(readMessage);
                    if (readMessage.equals("X")){
                        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                    }
                }
            }
        };
在textview中显示输入数据是可行的。但它无法识别输入数据中的X。然而,我可以看到这些数据正在文本视图中输入,并且我确实在de arduino代码中发送了这些数据

if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
    Serial.println("X");
  }

我确实知道代码是经过处理的,因为当我说if(!(readMessage.equals(“X”)){时,它会振动。

Arduinos Serial.print以ASCII发送。当你构建字符串时,你可以使用ASCII,比如:Charset.setName(“ASCII”),而不仅仅是“UTF-8”。这对我来说很好(使用Arduino Uno和HC-06蓝牙模块):

从byteBuffer创建的字符串应限制为实际数据的大小-您可以使用子字符串(0,sizeOfData)进行此操作

当我让我的应用程序与我的Arduino Uno连接时,我遇到了一个问题,根据配置,它忽略了Android中发送的第一个字节,所以尝试发送一个更长的字符串,看看你是否得到了什么,并且你实际上可以正确地读取它。 我建议您使用Serial.print而不是println,因为发送时不需要换行符。它还可能会更改您在Android上收到的消息

if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
Serial.print("X");
}


您也可以改用Serial.write,但不需要-看看这里的区别:

Arduinos Serial.print以ASCII格式发送。当您构建一个字符串时,可以像这样使用ASCII:Charset.setName(“ASCII”),而不仅仅是“UTF-8”。这对我来说很好(使用Arduino Uno和HC-06蓝牙模块):

从byteBuffer创建的字符串应限制为实际数据的大小-您可以使用子字符串(0,sizeOfData)进行此操作

当我让我的应用程序与我的Arduino Uno连接时,我遇到了一个问题,根据配置,它忽略了Android中发送的第一个字节,所以尝试发送一个更长的字符串,看看你是否得到了什么,并且你实际上可以正确地读取它。 我建议您使用Serial.print而不是println,因为发送时不需要换行。它还可能改变你在Android上收到的信息

if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
Serial.print("X");
}


您也可以使用Serial.write,但不需要-查看此处的差异:

您是否尝试过使用不同/更长的消息并检查是否可以阅读?Arduino用ASCII发送,我想…我试过了,但没用。你有没有试过记录你收到的消息,并确保UTF-8是正确的,而不是ASCII?我这么做了,我想这就是问题所在,数据在文本视图中显示为X,但当我记录时,它是一个问号。但是我不知道用什么来代替UTF-8,因为ASCII不是字符集名称。我将我的字符集名称更改为US-ASCII,但似乎没有任何改变,textview仍然正确显示输入数据,但在记录数据时,它有许多问号。我也试着解决这个问题,从文本视图中取回字符串,但这也会产生很多问题标记您是否尝试过使用不同/更长的消息并检查您是否可以阅读它?Arduino用ASCII发送,我想…我试过了,但没用。你有没有试过记录你收到的消息,并确保UTF-8是正确的,而不是ASCII?我这么做了,我想这就是问题所在,数据在文本视图中显示为X,但当我记录时,它是一个问号。但是我不知道用什么来代替UTF-8,因为ASCII不是字符集名称。我将我的字符集名称更改为US-ASCII,但似乎没有任何改变,textview仍然正确显示输入数据,但在记录数据时,它有许多问号。我也试着解决这个问题,从textview中取回字符串,但这也会产生很多问题Marks我能够让它工作,我确实按照你的建议将println改为print,并将“UTF-8”改为“US-ASCII”。我没有使用子字符串,而是在消息前面添加了一个随机字母,然后使用if(ReadMessage.contains(“x”))。谢谢你的建议。我很高兴能帮上忙!:-)我能够让它工作,我确实改变了println为打印,正如你所建议的,我改变了“UTF-8”为“US-ASCII”。我没有使用子字符串,而是在消息前面添加了一个随机字母,然后使用if(ReadMessage.contains(“x”))。谢谢你的建议。我很高兴能帮上忙!:-)