Android设备作为奴隶使用蓝牙时

时间:2011-11-11 08:01:19

标签: android bluetooth

有人能告诉我是否可以在使用蓝牙时将我的Android设备用作奴隶。我想要另一台设备(例如:PC)充当主人。我希望PC通过蓝牙连接到Android设备,然后从PC设备的超级终端接收来自Android设备的消息。

BR, Suppi

1 个答案:

答案 0 :(得分:2)

您需要创建一个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);
}