适用于Android的蓝牙示例

Nav*_*ron 6 android bluetooth

有没有人知道任何可用于说明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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我要求的是蓝牙的任何示例,更容易理解,以及明确区分蓝牙的服务器端和客户端的示例. 我有谷歌这个,我已经阅读了developer.android.com网站上提供的所有详细信息.

小智 9

从我所搜集的区别:仅在蓝牙连接正在建立服务器和客户端的情况下(即在发现和配对过程).对于要建立的连接,一个设备充当服务器(使用BluetoothServerSocket类的实例),另一个设备充当客户端(使用BluetoothSocket类的实例).(代理)服务器侦听传入请求,客户端请求侦听服务器进行连接.建立连接后(请参阅Android开发指南中使用的方法的详细信息),(最初调用的)服务器和客户端仅使用BluetoothSocket对象进行交互.所以不存在这样的服务器/客户端区别.

您可以在开发指南中查看蓝牙聊天示例的代码,尤其是BluetoothChatService类.调用方法createRfcommSocketToServiceRecord()将一个BluetotohSocket返回给侦听(服务器)设备.请求设备(客户端)使用类似的对象.

没错,进一步的示例代码会更好.