有没有人知道有没有可用的示例来说明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网站上所有可用的详细信息。