With the newest version of our software, I have some code to detect if there is no data being transferred from a Bluetooth connection. However, with our newest version of our software, some users are reporting that this code is being triggered even though the connection is fine. I haven't made any changes to this code ever since. I wonder if it is something different with the Android 12 Bluetooth stack that is causing something with this.
Note that I am unable to replicate this issue from my end, so this is apparently something that will be difficult to debug.
Here is my code:
//My connection monitor
public Runnable runnable = new Runnable() {
@Override
public void run() {
if (numBytes == 0) {
watchdogTimer++;
if (watchdogTimer == 10) {
dataTimeout = true;
eventHandler.obtainMessage(MESSAGE_CONN_TIMEOUT, 0, -1, "Connection Dead?").sendToTarget();
watchdogTimer = 0;
}
} else {
watchdogTimer = 0;
dataTimeout = false;
}
connectionMonitor.postDelayed(this, 1000);
}
};
//My byte reading code
public void run() {
byte j;
int lastone = 0;
while (isRunning) {
try {
if (inStream != null && btSocket.isConnected()) {
j = (byte) inStream.read();
if (j == -1)
continue;
if ((j == 0xA) && (lastone == 0xD)) {
//check for buffer overrun
if (readBytes.position() == PACKET_SIZE - 1) {
readBytes.put(j);
numBytes++;
dataReset = false;
if (dataTimeout) {
dataTimeout = false;
connectionMonitor.removeCallbacks(runnable);
connectionMonitor.postDelayed(runnable, 1000);
}
} else {
readBytes.clear();
numBytes = 0;
continue;
}
if (readBytes.position() == PACKET_SIZE) {
numSamples++;
if (bSendData) {
parseBytes(readBytes.array(), 0);
if (bWrite) {
write(readBytes.array());
}
}
if (dataTimeout) {
dataTimeout = false;
connectionMonitor.removeCallbacks(runnable);
connectionMonitor.postDelayed(runnable, 1000);
}
}
readBytes.clear();
numBytes = 0;
continue;
}
lastone = j;
if (readBytes.position() < PACKET_SIZE) {
dataTimeout = false;
readBytes.put(j);
numBytes++;
if (dataTimeout) {
dataTimeout = false;
connectionMonitor.removeCallbacks(runnable);
connectionMonitor.postDelayed(runnable, 1000);
}
} else {
readBytes.clear();
numBytes = 0;
//numSamples = 0;
}
} else {
throw new IOException("No Bluetooth Stream!");
}
} catch (IOException e) {
if (isRunning && watchdogTimer == 0) {
isRunning = false;
Log.e("Bluetooth", e.getMessage());
} else {
Log.e("ConnectedThread", "Interrupted");
}
}
}
}
Is there anything I can do to fix this? I would like a way to know if there is no data coming through but the tablet is still connected to the device, for I can display a warning message. Apparently some users are reporting they are randomly getting the message when they shouldn't be with our latest version of our software.