当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Creating conditions inside a Runnable in android

问题描述:

I've created a code that reads data thrown to my android device from an Arduino. It goes like this:

 public void run() {

byte[] buffer = new byte[1024];

int bytes;

final StringBuilder readMessage = new StringBuilder();

while (true) {

try {

bytes = connectedInputStream.read(buffer);

final String string_now = new String(buffer, 0, bytes);

readMessage.append(string_now);

// final int finalBytes = bytes;

runOnUiThread(new Runnable() {

@Override

public void run() {

tvBPM.setText(string_now);

readMessage.setLength(0);

}

});

} catch (IOException e) {

Toast.makeText(getApplicationContext(),"Connection Lost!",Toast.LENGTH_LONG).show();

}

}

}

This code is located inside my 'private class ThreadConnected extends Thread'

Now the values held by string_now are numbers. I want to tell the user if the value stored there is greater than 150 or less than 50. Here's a code I've tried but I doesn't fully work.

runOnUiThread(new Runnable() {

@Override

public void run() {

final int getValue = Integer.getValue(Integer.parseInt(string_now));

if (getValue > 150 || getValue < 50) {

Toast.makeText(getApplicationContext, "Unstable", Toast.LENGTH_SHORT).show(); }

else {

tvBPM.setText(string_now);

readMessage.setLength(0); }

}

});

Any tips on how I can make this work? Thank you.

网友答案:
bytes = connectedInputStream.read(buffer);
final String string_now = new String(buffer, 0, bytes);

This code will run forever even after the peer closes the connection, when it will start showing rubbish, giving ArrayIndexOutOfBoundsException, or whatever. You are missing the following between those two lines:

if (bytes == -1)
{
    break;
}

and the following after the catch block:

finally
{
    try
    {
        connectedInputStream.close();
    }
    catch (IOException exc)
    {
        // whatever ...
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: