我之前完成的所有蓝牙项目都有一个Android设备充当Master
,蓝牙加密狗或芯片充当单个Slave
。我正在处理的项目将使用Android平板电脑作为Master
,然后让其他几个Android设备充当Slaves
。
在这种情况下,最佳做法是什么?我应该写两个单独的申请吗?一个是主人,另一个是奴隶?或者两个卷使用一个应用程序是否合理?
答案 0 :(得分:1)
执行此操作的最佳方法是只创建一个应用程序,然后根据设备是主设备还是从设备,使用不同的代码逻辑。
您可以创建一种蓝牙"服务器"而不是只做一个简单的SPP连接。等到x个设备连接到服务器,然后在你的应用程序中做你想做的任何事情。
示例(来自开发人员指南:Here)
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket);
//in your case you wouldn't want to close the server socket since you want to
//connect more than one device. So keep listening until you get all the devices.
//you're also going to have to use different UUID's for each new device.
// mmServerSocket.close();
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
在这段代码中,一旦建立连接,服务器就会关闭,在这种情况下,你只需要继续监听更多套接字,直到获得所有套接字。您将需要多个线程来处理所有连接和一些同步,以根据您的意图处理来自所有连接的所有数据。