I have a small Android APP that connects the phone to a Scanner via Bluetooth. The APP connects and returns scan data as needed.
However, I need to be able to detect, and notify the user, when the scanner goes out of range and then auto-reconnect,
or have the user manually reconnect using a Dialog Box, when the Scanner is back in range.
I tried inserting a Timer that tries to connect every 10secs or so which opens a Dialog box
and stops the timer, but it did not work and it's real messy.
I thought there must be a simple method to do this.
Here is a truncated version of my current code
However, I need to be able to detect, and notify the user, when the scanner goes out of range and then auto-reconnect,
or have the user manually reconnect using a Dialog Box, when the Scanner is back in range.
I tried inserting a Timer that tries to connect every 10secs or so which opens a Dialog box
and stops the timer, but it did not work and it's real messy.
I thought there must be a simple method to do this.
Here is a truncated version of my current code
Code:
public class BluetoothListener {
private BluetoothSocket mmSocket; //
...
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
...
private void connect() {
try {
mmSocket.connect();
mListener = new StartListener(); mListener.start();
}
catch (IOException e) {
try { mmSocket.close(); } catch (IOException ex) {}
// Currently creates a working [reconnect]/[close] Dialog
mHandler.obtainMessage(2, "Dialog Alert".getBytes()).sendToTarget();
}
}
private class StartListener extends Thread {
private final InputStream mmInStream;
public StartListener() {
mState = LISTENING;
InputStream tmpIn = null;
try {
tmpIn = mmSocket.getInputStream();
}
catch (IOException e) {}
mmInStream = tmpIn;
}
public void run() {
try {
InputStreamReader mReader = new InputStreamReader(mmInStream, "UTF-8");
final BufferedReader bufferedReader = new BufferedReader(mReader);
String line = "";
while ((line=bufferedReader.readLine())!=null){
mHandler.obtainMessage(1, line.getBytes()).sendToTarget();
}
}
catch (Exception e) {}
}
...
}
...
}