使用蓝牙时将Android设备作为从设备
有人能告诉我,在使用蓝牙时,我是否可以将我的安卓设备用作从设备。我想要另一台设备(例如:PC)作为主机。我希望电脑通过蓝牙连接到Android设备,然后在电脑的超级终端上接收来自Android设备的消息 比尔,使用蓝牙时将Android设备作为从设备,android,bluetooth,Android,Bluetooth,有人能告诉我,在使用蓝牙时,我是否可以将我的安卓设备用作从设备。我想要另一台设备(例如:PC)作为主机。我希望电脑通过蓝牙连接到Android设备,然后在电脑的超级终端上接收来自Android设备的消息 比尔, Suppi您需要创建一个RFCOMM连接,您的Android设备将在其中侦听输入连接。下面是我自己的一些示例代码。BluetoothServiceEndpoint和BluetoothDeviceConnection是抽象接口,但在您的情况下,您不需要它们(只需使用Android API对
Suppi您需要创建一个RFCOMM连接,您的Android设备将在其中侦听输入连接。下面是我自己的一些示例代码。BluetoothServiceEndpoint和BluetoothDeviceConnection是抽象接口,但在您的情况下,您不需要它们(只需使用Android API对象)。如果可用,这段代码将使用未经验证的RFCOMM套接字(无配对)(仅来自Gingerbread,但它在以前的版本中工作,因为我使用反射) 您可以调用bind()然后accept()来接受连接
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);
}
非常感谢您的回复。我会试试这个,但我还有一个疑问。那么一台安卓设备是否可以同时作为从设备和主设备,但对于两台不同的设备,我从未尝试过这种配置。可以肯定的是,同一时间只能建立一个相同类型的连接(入站或出站)。另一方面,对于两种不同的连接类型(一种入站连接和一种出站连接),我不知道,但我打赌不知道。