安卓蓝牙示例

6

有没有人知道有没有可用的示例来说明Android上的蓝牙开发。

我已经阅读了这里的教程,我理解那一页上的所有内容。

然而,当涉及到将蓝牙代码实现到应用程序中时,有必要查看蓝牙聊天示例以了解它是如何工作的。

蓝牙聊天示例在这里

这个例子很好,但也很难理解,因为每个设备最初都被设置为服务器。

谁是服务器,两个设备是否都发送服务器套接字直到一个设备扫描?

一旦一个设备变得可发现,它就变成了服务器吗?

当OnResume活动开始时,因为一旦在SetupChat中初始化了mChatService,设备将启动一个Accept线程。

下面给出了一些代码示例,并且完整的蓝牙聊天链接可在上面找到。

@Override
public synchronized void onResume() {
    super.onResume();
    if(D) Log.e(TAG, "+ ON RESUME +");

    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
    if (mChatService != null) {
        // Only if the state is STATE_NONE, do we know that we haven't started already
        if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
          // Start the Bluetooth chat services
          mChatService.start();
        }
    }
}

private void setupChat() {

    // Initialize the BluetoothChatService to perform bluetooth connections
    mChatService = new BluetoothChatService(this, mHandler);

    // Initialize the buffer for outgoing messages
    mOutStringBuffer = new StringBuffer("");
}


/**
 * Start the chat service. Specifically start AcceptThread to begin a
 * session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
    if (D) Log.d(TAG, "start");

    // Cancel any thread attempting to make a connection
    if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

    setState(STATE_LISTEN);

    // Start the thread to listen on a BluetoothServerSocket
    if (mSecureAcceptThread == null) {
        mSecureAcceptThread = new AcceptThread(true);
        mSecureAcceptThread.start();
    }
    if (mInsecureAcceptThread == null) {
        mInsecureAcceptThread = new AcceptThread(false);
        mInsecureAcceptThread.start();
    }
}

我需要的是一些更易理解的蓝牙示例,以及明确区分蓝牙服务器端和客户端的示例。 我已经通过谷歌搜索和阅读了developer.android.com网站上所有可用的详细信息。

注意:如果使用HTC Hero手机,Android蓝牙会出现问题。上述代码在该手机上无法正常工作。 - Navigatron
1个回答

9
据我所了解,服务器和客户端的区别仅存在于蓝牙连接建立期间(即在发现和配对过程中)。为了建立连接,一个设备充当服务器(使用BluetoothServerSocket类的实例),另一个设备充当客户端(使用BluetoothSocket类的实例)。服务器(扮演角色)监听传入请求,而客户端请求正在侦听的服务器进行连接。连接建立后(请参阅Android Dev Guide上使用的方法的详细信息),初始调用的服务器和客户端仅使用BluetoothSocket对象进行交互。因此,不存在这样的服务器/客户端区别。
您可以查看Dev Guide上的蓝牙聊天示例代码,特别是BluetoothChatService类的代码。调用createRfcommSocketToServiceRecord()方法返回一个BluetotohSocket到侦听(服务器)设备。请求设备(客户端)则使用类似的对象。
确实,更多的示例代码会更好。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接