Reputation: 802
I was wondering, does anyone know how to connect to two Bluetooth SPP devices within the same app? I looked at the BluetoothChat
example, however, it doesn't give any information on how to connect to two Bluetooth SPP devices. I can't seem to find much information elsewhere either.
Upvotes: 2
Views: 911
Reputation: 1002
This Thread is inside my service class.
First, bind service and create a method in service class like this,
call this method and pass Bluetooth mac address. it will connect in the background. for the second device also follow the similar procedure.
public synchronized void connectToDevice(String macAddress){
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
if (mState == STATE_CONNECTING){
if (mConnectThread != null){
mConnectThread.cancel();
mConnectThread = null;
}
}
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectBtThread(device);
toast("connecting");
mConnectThread.start();
setState(STATE_CONNECTING);
}
Here i am creating Thread class to connect and run in background
private class ConnectBtThread extends Thread{
private final BluetoothSocket mSocket;
private final BluetoothDevice mDevice;
public ConnectBtThread(BluetoothDevice device){
mDevice = device;
BluetoothSocket socket = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(B_UUID));
} catch (IOException e) {
e.printStackTrace();
}
mSocket = socket;
}
@Override
public void run() {
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
try {
mSocket.connect();
Log.d("service","Bluetooth one running (connected)");
SharedPreferences pre = getSharedPreferences("BT_NAME",0);
pre.edit().putString("bluetooth_connected",mDevice.getName()).apply();
int i = 0;
Log.d("service","one + " +i++);
} catch (IOException e) {
try {
mSocket.close();
Log.d("service","connect thread run method ( close function)");
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
connected(mSocket);
}
public void cancel(){
try {
mSocket.close();
//Toast.makeText(getApplicationContext(),"Failed to connect one",Toast.LENGTH_SHORT).show();
Log.d("service","connect thread cancel method");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Similar to this create one more method and thread class to keep both Bluetooth devices in the Connected state. I followed this and its working fine for me.
Upvotes: 0
Reputation: 524
Let us assume we have two Bluetooth Devices B and C. To connect them we need
Bluetooth Sockets, one for each device.
Input and Output Streams to send messages.
Connection parameters: { Bluetooth Device(MAC Address), UUID }
To have multiple connections we must create these connection parameters dedicated to a connection.
Upvotes: 0