I'm looking for a way to gracefully disconnect from a Bluetooth device. I used the BluetoothChat sample and the problem is that when you intend to disconnect you simply call socket.close() from the cancel() method, but then the IntputStream.read() will inevitably throw an exception.
I need this mainly because it acts as a "lost connection" failsafe as well, so when I try to disconnect I get two signals: graceful disconnection followed by lost connection signal.
Basically what I'm trying to do is not to throw an exception in a method that will inevitably throw one:
while(true)
{
try
{
bytes = 0;
while((ch = (byte) inStream.read()) != '\0')
{
buffer[bytes++] = ch;
}
String msg = new String(buffer, "UTF-8").substring(0, bytes);
Log.v(TAG, "Read: " + msg);
}
catch(IOException e)
{
Log.e(TAG, "Failed to read");
// Inform the parent of failed connection
connectionEnd(STATE_LOST);
break;
}
}
And the extremely egoistic cancel():
public void cancel()
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
EDIT
This is the error code I get when I e.printStackTrace(); in catch:
09-06 13:05:58.557: W/System.err(32696): java.io.IOException: Operation Canceled
09-06 13:05:58.557: W/System.err(32696): at android.bluetooth.BluetoothSocket.readNative(Native Method)
09-06 13:05:58.557: W/System.err(32696): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:333)
09-06 13:05:58.557: W/System.err(32696): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:60)
09-06 13:05:58.557: W/System.err(32696): at com.bluetooth.BluetoothRemoteControlApp$ConnectedThread.run(BluetoothRemoteControlApp.java:368)
Try this:
Suppose you have out object of OutputStream and in object of InputStream, Then
inside your cancel close the connection like this:
public void cancel()
{
if(socket != null)
{
try {
out.close();
in.close();
socket.getOutputStream().close();
socket.close();
socket = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this help you
Solution: it's not perfect, but since there's no way of stopping the exception I made a disconnecting condidition:
catch(IOException e)
{
if(!disconnecting)
{
Log.e(TAG, "Failed to read");
e.printStackTrace();
// Inform the parent of failed connection
connectionEnd(STATE_LOST);
}
break;
}
disconnecting is set to true before calling the cancel() method. I'm not happy with it but it's not that ugly. I'm just not satisfied with the way the Bluetooth disconnection is handled (it works or it breaks).
Related
I am using a bluetooth library I found online called multibluetooth to connect a bunch of clients. I am testing with 2 android phones, 1 is running 5.0 and the other 6.0. Running a server on the 6.0 phone and a client on the 5.0 phone works but when I reverse the roles I get this error:
04-07 00:27:03.507 7499-8393/com.ramimartin.sample.multibluetooth W/BT: Fallback failed. Cancelling.
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:900)
at android.bluetooth.BluetoothSocket.waitSocketSignal(BluetoothSocket.java:859)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:535)
at com.ramimartin.multibluetooth.bluetooth.client.BluetoothConnector$FallbackBluetoothSocket.connect(BluetoothConnector.java:203)
at com.ramimartin.multibluetooth.bluetooth.client.BluetoothConnector.connect(BluetoothConnector.java:59)
at com.ramimartin.multibluetooth.bluetooth.client.BluetoothClient.run(BluetoothClient.java:54)
at java.lang.Thread.run(Thread.java:818)
Here is the part where I am getting the error:
public BluetoothSocketWrapper connect() throws IOException {
boolean success = false;
while (selectSocket()) {
adapter.cancelDiscovery();
try {
bluetoothSocket.connect();
success = true;
break;
} catch (IOException e) {
//try the fallback
try {
bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
bluetoothSocket.connect();
success = true;
break;
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
}
if (!success) {
throw new IOException("===> Could not connect to device: " + device.getAddress());
}
return bluetoothSocket;
}
Thank you in advance.
In case the disconnection happens while you leave the devices on sleep, this could be related with the Doze mode.
You can find more info at https://developer.android.com/training/monitoring-device-state/doze-standby.html .
Also feel free to ask me for more details.
I made android application that connects to remote server and send some data.
Remote server is Windows application.
Connection method:
private void ConnectToMonitor() {
try {
s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works perfectly if server is online. Application is sending data and server is receiving. But if server is offline android app. is blocked. My question is how to handle this? How to continue with application and avoid error even the server is down?
Remember to call this outside the UIThread.
Follow this tutorial. In android all connections need to be managed outside the UIThread, in the tutorial I linked you will find easy ways to post your results back to the UI (handlers, asynctasks...)
Of course we don't know if the problem is about the thread with just the given code, but it is the most usual error.
First remember to set the socket timeout :
mSocket.setSoTimeout(timeout); //in milliseconds
You can however specify different timeout for connection and for all other I/O operations through the socket:
private void connectToMonitor() {
try {
socket = new Socket();
InetAddress[] iNetAddress = InetAddress.getAllByName(SERVER_ADDRESS);
SocketAddress address = new InetSocketAddress(iNetAddress[0], TCP_SERVER_PORT);
socket.setSoTimeout(10000); //timeout for all other I/O operations, 10s for example
socket.connect(address, 20000); //timeout for attempting connection, 20 s
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Second, in Android, you should perform any network I/O in separate threads!
As an example, using regular Java Threads :
String threadName = getClass().getName() + "::connect";
new Thread(new Runnable() {
#Override
public void run() {
connectToMonitor();
}
}, threadName).start();
You can set A timeout for the socket. Use Socket.setSoTimeout method
socket.setSoTimeout(timesinmilis);
by using this your socket will throw a socket timout exception. You can catch that and do what you want
I'm trying to find a solution for this setup:
I have a single Android device, which I would like to connect to multiple serial embedded devices...
And here is the thing, using the "Normal" way to retrieve the Bluetooth socket, doesn't work on all devices, and while it does, I can connect to multiple devices, and send and receive data to and from multiple devices.
public final synchronized void connect()
throws ConnectionException {
if (socket != null)
throw new IllegalStateException("Error socket is not null!!");
connecting = true;
lastException = null;
lastPacket = null;
lastHeartBeatReceivedAt = 0;
log.setLength(0);
try {
socket = fetchBT_Socket_Normal();
connectToSocket(socket);
listenForIncomingSPP_Packets();
connecting = false;
return;
} catch (Exception e) {
socket = null;
logError(e);
}
try {
socket = fetchBT_Socket_Workaround();
connectToSocket(socket);
listenForIncomingSPP_Packets();
connecting = false;
return;
} catch (Exception e) {
socket = null;
logError(e);
}
connecting = false;
if (socket == null)
throw new ConnectionException("Error creating RFcomm socket for" + this);
}
private BluetoothSocket fetchBT_Socket_Normal()
throws Exception {
/* The getType() is a hex 0xXXXX value agreed between peers --- this is the key (in my case) to multiple connections in the "Normal" way */
String uuid = getType() + "1101-0000-1000-8000-00805F9B34FB";
try {
logDebug("Fetching BT RFcomm Socket standard for UUID: " + uuid + "...");
socket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
return socket;
} catch (Exception e) {
logError(e);
throw e;
}
}
private BluetoothSocket fetchBT_Socket_Workaround()
throws Exception {
Method m;
int connectionIndex = 1;
try {
logDebug("Fetching BT RFcomm Socket workaround index " + connectionIndex + "...");
m = btDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket) m.invoke(btDevice, connectionIndex);
return socket;
} catch (Exception e1) {
logError(e1);
throw e1;
}
}
private void connectToSocket(BluetoothSocket socket)
throws ConnectionException {
try {
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
logError("Error while closing socket", e1);
} finally {
socket = null;
}
throw new ConnectionException("Error connecting to socket with" + this, e);
}
}
And here is the thing, while on phones which the "Normal" way doesn't work, the "Workaround" way provides a solution for a single connection. I've searched far and wide, but came up with zip.
The problem with the workaround is mentioned in the last link, both connection uses the same port, which in my case, causes a block, where both of the embedded devices can actually send data, that is not been processed on the Android, while both embedded devices can receive data sent from the Android.
Did anyone handle this before?
There is a bit more reference here,
UPDATE:
Following this (that I posted earlier) I wanted to give the mPort a chance, and perhaps to see other port indices, and how other devices manage them, and I found out the the fields in the BluetoothSocket object are different while it is the same class FQN in both cases:
Detils from an HTC Vivid 2.3.4, uses the "workaround" Technic:
The Socket class type is: [android.bluetooth.BluetoothSocket]
mSocket BluetoothSocket (id=830008629928)
EADDRINUSE 98
EBADFD 77
MAX_RFCOMM_CHANNEL 30
TAG "BluetoothSocket" (id=830002722432)
TYPE_L2CAP 3
TYPE_RFCOMM 1
TYPE_SCO 2
mAddress "64:9C:8E:DC:56:9A" (id=830008516328)
mAuth true
mClosed false
mClosing AtomicBoolean (id=830007851600)
mDevice BluetoothDevice (id=830007854256)
mEncrypt true
mInputStream BluetoothInputStream (id=830008688856)
mLock ReentrantReadWriteLock (id=830008629992)
mOutputStream BluetoothOutputStream (id=830008430536)
**mPort 1**
mSdp null
mSocketData 3923880
mType 1
Detils from an LG-P925 2.2.2, uses the "normal" Technic:
The Socket class type is: [android.bluetooth.BluetoothSocket]
mSocket BluetoothSocket (id=830105532880)
EADDRINUSE 98
EBADFD 77
MAX_RFCOMM_CHANNEL 30
TAG "BluetoothSocket" (id=830002668088)
TYPE_L2CAP 3
TYPE_RFCOMM 1
TYPE_SCO 2
mAccepted false
mAddress "64:9C:8E:B9:3F:77" (id=830105544600)
mAuth true
mClosed false
mConnected ConditionVariable (id=830105533144)
mDevice BluetoothDevice (id=830105349488)
mEncrypt true
mInputStream BluetoothInputStream (id=830105532952)
mLock ReentrantReadWriteLock (id=830105532984)
mOutputStream BluetoothOutputStream (id=830105532968)
mPortName "" (id=830002606256)
mSocketData 0
mSppPort BluetoothSppPort (id=830105533160)
mType 1
mUuid ParcelUuid (id=830105714176)
Anyone have some insight...
WOW, every time this strike me down with one big WTF?
This was a race condition issue, which clearly works on one version of android, and not on another. On Android peer I was parsing the packets received from the socket:
public class SocketListener
implements Runnable {
private boolean stop;
private OnIncomingPacketListener packetListener;
#Override
public void run() {
InputStream inputStream;
try {
stop = false;
inputStream = socket.getInputStream();
while (!stop) {
Packet packet = Packet.getPacket(inputStream);
lastPacket = packet;
if (packet.getDescriptor() == Packet.HeartBeat)
lastHeartBeatReceivedAt = System.currentTimeMillis();
else if (packet.getDescriptor() == Packet.LogEntry)
log.append(((LogEntryPacket) packet).getLogEntry());
synchronized (this) {
if (packetListener != null)
packetListener.onIncomingData(EmbeddedDevice.this, packet);
}
}
} catch (IOException e) {
logError("----- BLUETOOTH IO ERROR -----\n #: " + EmbeddedDevice.this, e);
return;
} catch (RuntimeException e) {
logError("----- BLUETOOTH LISTENER ERROR -----\n #: " + EmbeddedDevice.this, e);
throw e;
} finally {
socketListeningThread = null;
}
}
}
Where the Packet.getPacket(inputStream) is:
public static synchronized Packet getPacketInstance(InputStream inputStream)
throws IOException {
int data = inputStream.read();
Packet type = null;
for (Packet packetType : values())
if (packetType.packetType == data) {
type = packetType;
break;
} // race condition here...
if (type == null)
throw new IllegalArgumentException("Unknown packet type: " + data);
try {
Packet packet = type.incomingPacketType.newInstance();
packet.setDescriptor(type);
packet.readPacketData(inputStream);
return packet;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Error instantiating type: " + type.incomingPacketType.getName(), e);
}
}
And every time a packet is completed, the next thread should have gone in to perform it parsing.
My guess is that there is some sort of lock on the port, that together with my implementation caused the second thread to block indefinitely, once I've removed the parsing to different instances per thread, the issue dissolved.
This insight was inspired by Daniel Knoppel, the guy from the mPort link.
Thanks Daniel!
I am trying to connect a bluetooth device from the Android phone. In most cases, the connection is successful.
I am making the socket connection using the following code:
if (isUsingHtcTypeConnectionScheme) {
try {
if (LOG_ENABLED) Log.d(TAG,"connecting to SPP with createRfcommSocket");
Method m = mRemoteDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
tmpSocket = (BluetoothSocket)m.invoke(mRemoteDevice, 1); // may be from 1 to 3
} catch (java.lang.NoSuchMethodException e){
Log.e(TAG, "java.lang.NoSuchMethodException!!!", e);
} catch ( java.lang.IllegalAccessException e ){
Log.e(TAG, "java.lang.IllegalAccessException!!!", e);
} catch ( java.lang.reflect.InvocationTargetException e ){
Log.e(TAG, "java.lang.InvocationTargetException!!!", e);
}
}
if (tmpSocket == null) {
try {
if (LOG_ENABLED) Log.d(TAG,"connecting to SPP with createRfcommSocketToServiceRecord");
tmpSocket = mRemoteDevice.createRfcommSocketToServiceRecord(uuid); // Get a BluetoothSocket for a connection with the given BluetoothDevice
} catch (IOException e) {
Log.e(TAG, "socket create failed", e);
}
}
mBtSocket = tmpSocket;
try {
mBtSocket.connect();
} catch (IOException e) {
connectionFailed();
setState(STATE_IDLE);
return;
}
And if the other device's bluetooth is not on, it will throw the IOException in 2-3 seconds, this is the normal behavior.
But sometimes the connection takes 20-30 seconds and eventually failed, and the other device's bluetooth is on.
I am wondering why this happens, if the phone cannot connect to device, it should throw IOException in 2-3 seconds. But now is taking 20-30 seconds to throw the IOException. (And the other device is ready for connection actually)
I tested on several Android phones and also have this problem, so may not be related to specific phone.
Any ideas?
Thanks!
I'm developing a program in which, from an Android Phone, I have to connect as a client to a Bluetooth medical sensor. I'm using the official Bluetooth API and no problem during connection (SPP profile), but when I end the socket, the sensor is still connected to my phone (although I have close the connection).
Are there any way to make a Bluetooth disconnection? I think there is an intent called ACTION_ACL_CONNECTED, which does that. Can anyone explain me how to use this?
Thanks in advance.
EDITED: Here is the code, if anyone needs additional info, it's a Nonin 4100 medical sensor.
Set<BluetoothDevice> pairedDevices = Activa.myBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
String name = device.getName();
if (name.contains("Nonin")) {
try {
found = true;
// socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
// handler.sendEmptyMessage(5);
// Activa.myBluetoothAdapter.cancelDiscovery();
// socket.connect();
BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress());
Method m;
try {
m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1));
handler.sendEmptyMessage(5);
socket.connect();
} catch (Exception e) {
handler.sendEmptyMessage(7);
e.printStackTrace();
break;
}
handler.sendEmptyMessage(6);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] retrieve = { 0x44, 0x31};
out.write(retrieve);
byte [] ack = new byte [1];
in.read(ack);
if (ack[0] == 0x15) {
cancelMeasurement();
return;
}
byte [] data = new byte [3];
long timeStart = System.currentTimeMillis();
this.timePassed = System.currentTimeMillis() - timeStart;
while ((this.timePassed < (this.time))&&(this.finished)) {
try {
in.read(data);
processData(data);
Thread.sleep(1000);
this.timePassed = System.currentTimeMillis() - timeStart;
} catch (Exception e) {
e.printStackTrace();
}
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please remember to close your Input/output streams first, then close the socket.
By closing the streams, you kick off the disconnect process. After you close the socket, the connection should be fully broken down.
If you close the socket before the streams, you may be bypassing certain shutdown steps, such as the (proper) closing of the physical layer connection.
Here's the method I use when its time to breakdown the connection.
/**
* Reset input and output streams and make sure socket is closed.
* This method will be used during shutdown() to ensure that the connection is properly closed during a shutdown.
* #return
*/
private void resetConnection() {
if (mBTInputStream != null) {
try {mBTInputStream.close();} catch (Exception e) {}
mBTInputStream = null;
}
if (mBTOutputStream != null) {
try {mBTOutputStream.close();} catch (Exception e) {}
mBTOutputStream = null;
}
if (mBTSocket != null) {
try {mBTSocket.close();} catch (Exception e) {}
mBTSocket = null;
}
}
EDIT: Adding code for connect():
// bluetooth adapter which provides access to bluetooth functionality.
BluetoothAdapter mBTAdapter = null;
// socket represents the open connection.
BluetoothSocket mBTSocket = null;
// device represents the peer
BluetoothDevice mBTDevice = null;
// streams
InputStream mBTInputStream = null;
OutputStream mBTOutputStream = null;
static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
/**
* Try to establish a connection with the peer.
* This method runs synchronously and blocks for one or more seconds while it does its thing
* SO CALL IT FROM A NON-UI THREAD!
* #return - returns true if the connection has been established and is ready for use. False otherwise.
*/
private boolean connect() {
// Reset all streams and socket.
resetConnection();
// make sure peer is defined as a valid device based on their MAC. If not then do it.
if (mBTDevice == null)
mBTDevice = mBTAdapter.getRemoteDevice(mPeerMAC);
// Make an RFCOMM binding.
try {mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
} catch (Exception e1) {
msg ("connect(): Failed to bind to RFCOMM by UUID. msg=" + e1.getMessage());
return false;
}
msg ("connect(): Trying to connect.");
try {
mBTSocket.connect();
} catch (Exception e) {
msg ("connect(): Exception thrown during connect: " + e.getMessage());
return false;
}
msg ("connect(): CONNECTED!");
try {
mBTOutputStream = mBTSocket.getOutputStream();
mBTInputStream = mBTSocket.getInputStream();
} catch (Exception e) {
msg ("connect(): Error attaching i/o streams to socket. msg=" + e.getMessage());
return false;
}
return true;
}
I found that if I call socket.close() too soon after a recent communication via the OutputStream, then the close fails and I cannot reconnect. I added a Thread.sleep(1000) just prior to the call to close() and this seems to solve it.
HI,
I've seen the exact same problem (HTC Desire).
Despite closing the socket by the book (as Brad suggests), the next connect() blocks forever - until ended by close() by another thread.
I circumvented the problem by always calling BluetoothAdapter.disable()/.enable() before connecting. Awful, unfriendly hack, I know...
I suspect that some of the present BT issues are manufacturer specific, as some app implementors seem to live happily with createRfcommSocketToServiceRecord(), which definitely fails on my HTC Desire (Android 2.1 update 1).
I have seen indications (sorry, don't have references) that HTC Desire's BT stack differs from the Nexus One, although they seem to be very similar devices...
BR
Per
(addition)
Here's a very simple activity to reproduce the problem (without my disable/enable 'cure'):
package com.care2wear.BtTest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class BtTestActivity extends Activity {
private static final String TAG="BtTest";
BluetoothAdapter mBtAdapter = null;
BluetoothDevice mBtDev = null;
BluetoothSocket mBtSocket = null;
InputStream isBt;
OutputStream osBt;
String mAddress = "00:18:E4:1C:A4:66";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
connect(); // ok
disconnect(); // ok
connect(); // this invariably fails - blocked until BT is switched off by someone else, or the peer device turns off/goes out of range
disconnect();
}
private void init() {
Log.d(TAG, "initializing");
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
mBtDev = mBtAdapter.getRemoteDevice(mAddress);
Log.d(TAG, "initialized");
}
private void connect() {
try {
Log.d(TAG, "connecting");
Method m = mBtDev.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
mBtSocket = (BluetoothSocket) m.invoke(mBtDev, 1);
mBtSocket.connect();
Log.d(TAG, "connected");
} catch (SecurityException e) {
Log.e(TAG, "SecEx", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "NsmEx", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "IArgEx", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "IAccEx", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "ItEx", e);
} catch (IOException e) {
Log.e(TAG, "IOEx", e);
}
}
private void disconnect() {
Log.d(TAG, "closing");
if (isBt != null) {
try {
isBt.close();
} catch (IOException e) {
Log.e(TAG, "isBt IOE", e);
}
isBt = null;
}
if (osBt != null) {
try {
osBt.close();
} catch (IOException e) {
Log.e(TAG, "osBt IOE", e);
}
osBt = null;
}
if (mBtSocket != null) {
try {
mBtSocket.close();
} catch (IOException e) {
Log.e(TAG, "socket IOE", e);
}
mBtSocket = null;
}
Log.d(TAG, "closed");
}
}
If anyone can spot if I'm doing it wrongly, feel free to comment :)
(addition 2)
I think I got it to work now:
The official method of connecting RFCOMM (via SDP) now actually seems to work (HTC Desire, 2.1 update 1), BUT I had to remove and re-pair the BT device. Go figure..
Reconnection may still fail (service discovery failure) if I reconnect 'too quickly' (quit app, then immediately restart). Guess the connection is not completely down yet..
If I always end the (last) activity not only with finish(), but also with Runtime.getRuntime().exit(0);, it works a lot better. Go figure again...
If anyone can explain this, I'll happily learn.
/Per
(addition 3)
Finally got the Froyo (2.2) update for my Desire, and as far as I can see, SPP now works :)
/Per
I was developing an app that conects to a BT device. Your code works fine in my HTC Wildfire but with a Samsung Galaxy I5700 doen't work. Both os are 2.1 update but.....
The exception was 'InvocationTargetException'
The only thing I had to modify is the disconnect().
private void disconnect() {
if(Conectado){
try {
***mBtSocket.close();***
texto.setText(texto.getText()+"\nDesconectado");
Conectado = false;
} catch (IOException e1) {
// TODO Auto-generated catch block
texto.setText(texto.getText()+"\n"+e1.getMessage());
}
catch (Exception e2) {
// TODO Auto-generated catch block
texto.setText(texto.getText()+"\n"+e2.getMessage());
}
}
Hey so I have been using the Bluetooth Chat application from The Android Development site and they provide a stop() method in BluetoothChatService class. So I simply created an instance of it in my main class and and called the stop function from my disconnect button.
Here is how I call it in my main class
// Member object for the chat services
private BluetoothManager mChatService = null;
case R.id.disconnect:
mChatService.stop();
break;
The stop() method in BluetoothChatService
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
public synchronized void stop()
{
if (mConnectThread != null)
{
mConnectThread.cancel(); mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.cancel(); mConnectedThread = null;
}
if (mAcceptThread != null)
{
mAcceptThread.cancel(); mAcceptThread = null;
}
}
I have the same Issue.
This is the trouble with the Bluetooth Module CSR BC417, present in many devices as serial to bluetooth adapter with SPP profile.
With another Bluetooth module android device works well, and the bluetooth release the conection after the socket is closed,
but with devices with this CSR core not.
Tested on SPP Bluetooth to Serial Adaptor based on CSR BC417, and Bluetooth module from Actisys.
Both with Android 4.0 devices.
I dont know why but is a compatibility issue between harwares, try to change the serial adaptor for another with a different Core.
I tryout programatically to find a solution, even disabling a bluetooth, but is impossible, the trouble is originated on the CSR module.