来自message.obj的字符串不适用于比较条件

时间:2017-11-09 15:51:51

标签: java android

我从Message类中获取一条消息并将其放入字符串ss中,现在每次我得到字符串HOME我发送消息dir,但它从不发送消息

我不确定为什么但是第一个条件永远不会满足,即使ss是HOME这是证据,因为tv.settext变成了HOME(我已经测试了这个多次)

TextView tv = (TextView) findViewById(R.id.readField);
ss=(String) message.obj;
if(ss.equals("HOME")) {
   Message msg = Message.obtain();
   msg.obj = dir;
   writeHandler.sendMessage(msg);
}
else {
   tv.setText(ss);
}

1 个答案:

答案 0 :(得分:0)

阅读部分代码以了解上述代码

/**
 * Return data read from the socket, or a blank string.
 */
private String read() {

    String s = "";

    try {
        // Check if there are bytes available
        if (inStream.available() > 0) {

            // Read bytes into a buffer
            byte[] inBuffer = new byte[1024];
            int bytesRead = inStream.read(inBuffer);

            // Convert read bytes into a string
            s = new String(inBuffer, "ASCII");
            s = s.substring(0, bytesRead);
        }

    } catch (Exception e) {
        Log.e(TAG, "Read failed!", e);
    }

    return s;
}

 //Under Message class
 //Message coding
 private void sendToReadHandler(String s) {

    Message msg = Message.obtain();
    msg.obj = s;
    readHandler.sendMessage(msg);
    Log.i(TAG, s);
}

/**
 * Send complete messages from the rx_buffer to the read handler.
 */
private void parseMessages() {

    // Find the first delimiter in the buffer
    int inx = rx_buffer.indexOf(DELIMITER);

    // If there is none, exit
    if (inx == -1)
        return;

    // Get the complete message
    String s = rx_buffer.substring(0, inx);

    // Remove the message from the buffer
    rx_buffer = rx_buffer.substring(inx + 1);

    // Send to read handler
    sendToReadHandler(s);

    // Look for more complete messages
    parseMessages();
}

public void run() {

    // Attempt to connect and exit the thread if it failed
    try {
        connect();
        sendToReadHandler("CONNECTED");
    } catch (Exception e) {
        Log.e(TAG, "Failed to connect!", e);
        sendToReadHandler("CONNECTION FAILED");
        disconnect();
        return;
    }

    // Loop continuously, reading data, until thread.interrupt() is called
    while (!this.isInterrupted()) {

        // Make sure things haven't gone wrong
        if ((inStream == null) || (outStream == null)) {
            Log.e(TAG, "Lost bluetooth connection!");
            break;
        }

        // Read data and add it to the buffer
        String s = read();
        if (s.length() > 0)
            rx_buffer += s;

        // Look for complete messages
        parseMessages();
    }

    // If thread is interrupted, close connections
    disconnect();
    sendToReadHandler("DISCONNECTED");
}
}