Android蓝牙串口通信的用法(二)

2018-06-07  本文已影响0人  未丑

如果需要开发接收端,需要等待对方的数据的话:

class SocketListener extends Thread {
private BluetoothServerSocket mmServerSocket;//test
private BluetoothAdapter mAdapter;
private static final String NAME_SECURE = "BluetoothSecure";

 // Unique UUID for this application
 private final UUID MY_UUID_SECURE = UUID
 .fromString("00001101-0000-1000-8000-00805F9B34FB");

  public SocketListener() {

mAdapter = BluetoothAdapter.getDefaultAdapter();
Log.d(TAG, "mmServerSocket.adapter");
}

    @Override
    public void run() {
        try {

         Log.d(TAG, "mmServerSocket.run");
         mmServerSocket=mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE);

         Log.d(TAG, "listenUsingRfcommWithServiceRecord");
         BluetoothSocket socket = null;
            while (true) {

             socket = mmServerSocket.accept();

             Log.d(TAG, "mmServerSocket.accept");

                if (socket != null) {
                 SocketReadThread rt = new SocketReadThread();
                 rt.setLocalSocket(socket);
                 Thread thread = new Thread(rt);
                    thread.start();

                    Log.d(TAG, "SocketReadThread.start--BT");

                }

            }
        } catch (IOException e) {

         Log.d(TAG, "mmServerSocket.exception");
         Log.e(getClass().getName(), e.getMessage());
         e.printStackTrace();
        }
    }
}

线程SocketReadThread中的关键代码:
public void setLocalSocket(BluetoothSocket socket)
{

        try {
            input = socket.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

run里面的部分:
DataInputStream is = new DataInputStream(input);
byte[] bytes = new byte[1024];//1k
while ((readnum=is.read(bytes)) != -1) {
//数据处理

}

等于是在接收端发起一个accept,接收对方的connect,成功后就会启动数据read线程,while里面read是阻塞的。

上一篇 下一篇

猜你喜欢

热点阅读