gpt4 book ai didi

android - 如何在android中通过蓝牙连接并向多个设备发送消息?

转载 作者:太空狗 更新时间:2023-10-29 13:36:22 24 4
gpt4 key购买 nike

我想开发一个通过蓝牙向多个设备发送消息的应用程序。我知道蓝牙是一种点对点通信,即使我想按照以下步骤连接并发送消息:

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();
}




}
});

从上面的代码中,我在循环 pairedList.get(0) 时获得了连接。但是消息没有发送到另一个设备。在另一个设备中安装了 api 示例应用程序。

如果我使用 pairedList.get(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);
}

然后调用这个方法,这个方法也在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 屏幕更新的处理程序报告任何读取的信息

关于android - 如何在android中通过蓝牙连接并向多个设备发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com