Could someone tell me if i can use my android device as a slave while using Bluetooth. I want another device (for example: PC) to act as a Master. I want the PC to connect to the Android device via Bluetooth and then receive messages from the Android device say on the hyper terminal of the PC.
BR, Suppi
You need to create a RFCOMM connection where your Android device will listen to incomming connections. Here is some sample code of my own. BluetoothServiceEndpoint and BluetoothDeviceConnection are abstraction interfaces, but in your case you do not need them (just use Android API objects). This chunk of code will use an unauthenticated RFCOMM socket (without pairing) if available (only from Gingerbread, but it works in previous versions since I use reflection).
You would call bind() and then accept() to accept connections.
public void bind() throws IOException
{
if (serverSocket != null)
{
throw new IOException("Service already bound");
}
UUID serviceUUID = UUID.fromString(localServiceEndpoint.getUuid()
.toRFC4122String());
boolean boundWithAuthentication = false;
if (!localServiceEndpoint.isAuthenticationRequired())
{
serverSocket = listenUsingInsecureRfcommWithServiceRecord(
localServiceEndpoint.getServiceName(), serviceUUID);
}
if (serverSocket == null)
{
/*
* Si no hemos podido utilizar un socket inseguro (sin
* autenticación) aunque se haya solicitado así usamos uno seguro.
*/
serverSocket = ba.listenUsingRfcommWithServiceRecord(
localServiceEndpoint.getServiceName(), serviceUUID);
boundWithAuthentication = true;
}
int usedChannel = getUsedChannelPrivate(serverSocket);
remoteServiceEndpoint = new BluetoothServiceEndpoint(
BluetoothServiceEndpoint.TYPE_SPP, ba.getAddress().replaceAll(
":", ""), usedChannel, null,
localServiceEndpoint.isAuthenticationRequired());
info("Service bound " + (boundWithAuthentication ? "with" : "without")
+ " authentication");
}
private BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(
String serviceName, UUID serviceUUID)
{
BluetoothServerSocket socket = null;
try
{
Method m = ba.getClass().getMethod(
"listenUsingInsecureRfcommWithServiceRecord", String.class,
UUID.class);
socket = (BluetoothServerSocket) m.invoke(ba, serviceName,
serviceUUID);
}
catch (Exception e)
{
warn("Unable to bind service without authentication. This device does not support API level >= 10");
}
return socket;
}
public BluetoothDeviceConnection accept() throws IOException
{
if (serverSocket == null)
{
throw new IOException("Service not bound");
}
BluetoothSocket socket = serverSocket.accept();
return new BluetoothDeviceConnectionImpl(new AndroidNativeConnection(
socket), params, listener, logger);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With