如何在android中通过蓝牙连接并向多个设备发送消息?
我想开发一个应用程序,通过Bluetooth向多个设备发送消息。我知道Bluetooth是一种点对点通信,尽管我想按照以下步骤连接并发送消息: 1.获取配对设备的列表 2.从配对列表中选择一个设备 3.连接到配对设备,向所选配对设备发送消息 4.断开与设备的连接 5.连接到另一个设备等(一个接一个) 我将获得配对设备地址列表,如下所示:如何在android中通过蓝牙连接并向多个设备发送消息?,android,bluetooth,connection,mobile-devices,Android,Bluetooth,Connection,Mobile Devices,我想开发一个应用程序,通过Bluetooth向多个设备发送消息。我知道Bluetooth是一种点对点通信,尽管我想按照以下步骤连接并发送消息: 1.获取配对设备的列表 2.从配对列表中选择一个设备 3.连接到配对设备,向所选配对设备发送消息 4.断开与设备的连接 5.连接到另一个设备等(一个接一个) 我将获得配对设备地址列表,如下所示: mBtAdapter = BluetoothAdapter.getDefaultAdapter(); Set<Bluetoot
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();
}
}
});
mBtAdapter=BluetoothAdapter.getDefaultAdapter();
Set pairedDevices=mBtAdapter.getBondedDevices();
如果(pairedDevices.size()>0){
用于(蓝牙设备:pairedDevices){
add(device.getAddress());
}
Log.v(“11111111”、“11111111”+dev);
}
我正在尝试连接到它们,并在用户单击按钮时发送消息,如下所示:
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();
}
}
});
((按钮)findViewById(R.id.button1)).setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
字符串消息=“haii”;
对于(int i=0;i尝试为每个连接创建单独的线程-我有一个类似的问题,为每个连接创建一个新线程很好地解决了它。顺便说一句,我甚至创建了一个新线程来建立连接-因此建立连接不会阻塞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);
}
然后要编写,只需调用这个方法,这个方法也是在ConnectionReadBT中定义的
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屏幕更新的处理程序报告所有读取信息