【发布时间】:2011-11-11 08:01:19
【问题描述】:
有人能告诉我在使用蓝牙时是否可以将我的安卓设备用作从设备。我希望另一台设备(例如:PC)充当主设备。我希望 PC 通过蓝牙连接到 Android 设备,然后在 PC 的超级终端上接收来自 Android 设备的消息。
BR, 补充
【问题讨论】:
有人能告诉我在使用蓝牙时是否可以将我的安卓设备用作从设备。我希望另一台设备(例如:PC)充当主设备。我希望 PC 通过蓝牙连接到 Android 设备,然后在 PC 的超级终端上接收来自 Android 设备的消息。
BR, 补充
【问题讨论】:
您需要创建一个 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);
}
【讨论】: