我想开发一个通过蓝牙向多个设备发送消息的应用程序。我知道蓝牙是一种点对点通信,即使我想按照以下步骤连接并发送消息:
1.获取配对设备列表
2.从配对列表中选择设备
3.连接到配对设备,向所选配对设备发送消息
4.从设备断开
5.获取与其他设备的连接等(一个接一个)。
我正在获得配对设备地址列表如下:
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedList.add(device.getAddress());
}
Log.v("11111111", "11111111111"+dev);
}
我正在尝试连接它们并在用户点击按钮时发送消息,如下所示:
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String message = "Haiii";
for(int i=0;i<dev.size();i++){
Log.v("device", "111111 : "+pairedList.get(i));
mbService.connect(mBtAdapter.getRemoteDevice(pairedList.get(i)));
mbService.write(message.getBytes());
mbService.stop();
}
}
});
从上面的代码我得到了loop pairedList.get(0)时的连接。但是消息没有发送到另一个设备。在另一个设备api示例应用程序已安装。
如果我使用pairedList.get(i)它也不会连接到任何设备,即使是单个设备。
请帮帮我。
答案 0 :(得分:2)
尝试为每个连接创建单独的线程 - 我有一个类似的问题,为每个连接创建一个新线程很好地解决了它。顺便说一句,我甚至创建一个新线程来建立连接 - 因此建立连接不会阻止UI。从BT示例代码中得到了这个......
创建一个新线程来建立连接:
mConnectBluetoothThread = new ConnectBluetoothThread(device);
mConnectBluetoothThread.start();
其中ConnectBluetoothThread的定义如下:
public ConnectBluetoothThread(BluetoothDevice device) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
// TODO
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(this.getClass().getSimpleName(),
"unable to close() socket during connection failure",
e2);
}
return;
}
// Reset the ConnectThread because we're done
synchronized (InterBT.this) {
mConnectBluetoothThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(),
"close() of connect socket failed", e);
}
}
}
public synchronized void connected(BluetoothSocket socket,
BluetoothDevice device) {
if (DEBUG)
Log.d(this.getClass().getSimpleName(), "connected");
// Cancel the thread that completed the connection
if (mConnectBluetoothThread != null) {
mConnectBluetoothThread.cancel();
mConnectBluetoothThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedBluetoothThread != null) {
mConnectedBluetoothThread.cancel();
mConnectedBluetoothThread = null;
}
// Cancel the accept thread because we only want to connect to one
// device
// if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread =
// null;}
// Start the thread to manage the connection and perform transmissions
mConnectedBluetoothThread = new ConnectionThreadBT(socket);
mConnectedBluetoothThread.start();
setState(STATE_CONNECTED);
}
并创建一个新的类ConnectionThreadBT
来处理读写连接:
public class ConnectionThreadBT extends ConnectionThreadBase {
private static final boolean DEBUG = true;
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
byte[] responseBuffer = new byte[4096 * 4];
int responseBufferLen = 0;
public ConnectionThreadBT(BluetoothSocket socket) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "temp sockets not created",
e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
this.getClass().getName()
+ " ->"
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
//we have successfully connected to BT
//now inform UI
Home_Screen.sendMessageToHomeScreen(
Home_Screen.MESSAGE_INTERBT_CONNECTION_TESTED,
Home_Screen.CONNECTION_SUCCESS, true);
}
然后写入只调用此方法,该方法也在ConnectionThreadBT中定义
public void sendMsg(MyBuffer buffer){
try {
mmOutStream.write(buffer);
mmOutStream.flush();
successfullyWritten = true;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(),
"Exception during write", e);
successfullyWritten = false;
}
要么执行相同操作,要么在run方法中启动监视循环,只要connectedThread处于活动状态,就会继续读取,并通过类似于UI屏幕更新的处理程序报告任何读取信息