I have downloaded the android sample of Bluetooth chat app to send text between two android devices using Bluetooth.
I have installed and run this app in two android devices.
I faced many problems in that code
- Service discovery failed exception - Fixed
- java.io.IOException: Software caused connection abort - Fixed
- java.io.IOException: Connection reset by Peer - Struck on this
1. Cleared the Service discovery failed exception:
For service discovery failed exception, In Bluetooth Chat Service, I have checked sdk version and for the sdk version which is greater than Ginger Bread,
I have used Method class to invoke RfCOMM socket connection and my first exception is solved in this approach.
Exception Code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Fixed Exception code
try {
if (Build.VERSION.SDK_INT < 9) {
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e(TAG, "create() failed", e);
}
2. Cleared java.io.IOException: Software caused connection abort
I have made check whether the InputStream is available
Exception Code
bytes = mmInStream.read(buffer);
Fixed Exception code
if (mmInStream.available() > 0) {
// Read from the InputStream
bytes = mmInStream.read(buffer);
Now my problem is when I try to send data between connected devices, it throws the following error message "Connection Reset By Peer" while writing to output stream
Exception code:
public void write(byte[] buffer, int start, int end) {
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
if (mmOutStream !=null) {
try {
mmOutStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Log.e("OutputStream Null","");
}
}
== Update ==
Even though it shows that both devices are connected, the accept method returns fail
**06-19 10:30:23.625: D/BluetoothChatService(2630): connected
06-19 10:30:23.625: D/BluetoothChatService(2630): cancel Thread[AcceptThread,5,main]
06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): abortNative
06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): ...asocket_abort(50) complete
06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): ...accept(50, RFCOMM) = -1 (errno 125)
06-19 10:30:23.632: E/BluetoothChatService(2630): accept() failed
06-19 10:30:23.632: E/BluetoothChatService(2630): java.io.IOException: Operation Canceled
06-19 10:30:23.632: E/BluetoothChatService(2630): at android.bluetooth.BluetoothSocket.acceptNative(Native Method)