2011-05-26 90 views
5

有谁知道任何可用的示例,说明Android上的蓝牙开发。适用于Android的蓝牙示例

我已阅读教程here,我了解该页面上的所有内容。

但是,当涉及到实施蓝牙代码时,需要查看蓝牙聊天示例以了解它是如何工作的。

蓝牙聊天例如here

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

谁是服务器,并且两台设备都会发送服务器套接字,直到一台设备扫描完成为止?

一旦设备自己发现它会成为服务器?

什么时候OnResume活动开始,因为一旦启动并且mChatService已经在SetupChat中初始化,设备将启动一个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(); 
    } 
} 

我所要求的是明确分离服务器端和蓝牙的客户端蓝牙的任何例子,更易于理解和实例。 我已经Google'd这个,并且我已经阅读了developer.android.com网站上的所有详细信息。

+0

注意:如果使用的HTC Hero有一个与Android的蓝牙问题。上面的代码无法正确工作。 – Navigatron 2013-06-04 13:35:11

回答

9

从我所收集的内容来看,区别在于:服务器和客户端仅在蓝牙连接建立时(即在发现和配对过程中)存在。为了建立连接,一个设备充当服务器(使用BluetoothServerSocket类的实例),另一个充当客户端(使用BluetoothSocket类的实例)。 (作用)服务器侦听传入请求并且客户端请求侦听服务器进行连接。建立连接后(请参阅Android开发人员指南中使用的方法的详细信息),(最初称为)服务器和客户端都只使用BluetoothSocket对象进行交互。所以不存在这样的服务器/客户端区别。

您可以检查出的开发指南蓝牙聊天例子的代码,特别是BluetoothChatService类的。调用方法createRfcommSocketToServiceRecord()会向侦听(服务器)设备返回一个BluetotohSocket。请求设备(客户端)使用类似的对象。

True时,进一步的示例代码会更好。