3

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

1.获取配对设备列表

2.从配对列表中选择一个设备

3.连接到配对设备,向选定的配对设备发送消息

4.断开与设备的连接

5.Get连接到另一台设备等等(一个接一个)。

我正在获取配对设备地址列表,如下所示:

       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) 它不会连接到任何设备,甚至是单个设备。

请帮我 。

4

1 回答 1

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

to read either do the same or start a monitoring loop in the run method which keeps reading as long as the connectedThread is alive and reports back any read information through a handler similar to the UI screen update

于 2012-04-10T06:29:39.163 回答