In my Android application i send and receive data through Bluetooth to/from an Embedded Hardware device. I use a background Service to achieve this. To read bluetooth data, i use my below code,
public void run() {
Log.d("DEBUG BT", "IN CONNECTED THREAD RUN");
byte[] buffer = new byte[10240]; //1kb=1024bytes
int begin = 0;
int bytes = 0;
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
System.out.println("-------------New Data received");
al = new ArrayList<>();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("InterruptedException during sleep");
}
// Read from the InputStream.
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
// Send the obtained bytes to the UI activity.
bluetoothIn.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Problem in reading Data:Input stream was disconnected "+e.getMessage());
Handler hand = new Handler(Looper.getMainLooper());
hand.post(new Runnable() {
@Override
public void run() {
Toast.makeText(BluetoothDataService.this.getApplicationContext(),"Problem in reading Data",Toast.LENGTH_SHORT).show();
dismissDialog();
}
});
break;
}
}
}
I will send query to my Hardware unit and will be waiting for data through Bluetooth, but i didnot know how to check for timeout, I use Progress bar till i receive data but sometimes If i didnot receive data for more than 20 secs i need to alert user as "Timeout" but in my case progress is still loading ,i am stuck how to achieve this,please someone suggest how to check for timeout