I am trying to connect from a desktop application (written in Java) to a Android application through Bluetooth.
For the desktop application I am using BlueCove API.
When I start the server (desktop application) and I start the Android application, the connection works fine. (i.e. The client sends a "Hello World" and the server prints it in the console). But when I leave the application (by pressing Back or Home button) and return back to it, the socket connection seems to be lost.
How can you check if a Bluetooth socket is already connected?
I would like to check the connection of the socket to not having connecting again.
What should I write (if it is the case) in the onPause
, onResume
methods?
I suppose that in the onDestroy
method I should close the socket.
Here is the source code of the client server:
Server
Client
I also tried using IntentFilter
to check for the state of the connection, but it didn't work.
@Override
public void onCreate(Bundle savedInstanceState) {
// .....
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Device found
Toast.makeText(BluetoothClient.this, "Device not found", 2).show();
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Toast.makeText(BluetoothClient.this, "Device connected", 2).show();
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
Toast.makeText(BluetoothClient.this, "Done searching", 2).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
Toast.makeText(BluetoothClient.this, "Device about to connect", 2).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
Toast.makeText(BluetoothClient.this, "Device disconnected", 2).show();
}
}
};