Android 2.1 蓝牙 SPP 中使用 Inputstream.read 时出错

发布于 2024-09-24 15:50:19 字数 2346 浏览 4 评论 0原文

我尝试连接蓝牙适配器,它在发送握手后向我发送一些数据。 我的问题是,在适配器发送之前,代码工作正常,但如果它停止, in.read(xxx 命令会阻塞,没有任何异常。我必须关闭适配器并等待几秒钟,然后发生异常,并且代码恢复。 怎么解决这个问题呢? (为了更好地理解,我删除了错误处理)

BluetoothAdapter bt_adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bt_device = null;

//Bluetooth not supportet
if (bt_adapter == null) {
    return false;
}

//enable Bluetooth
if (!bt_adapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    return false;
}    

//search K01-Blue Adapter
Set<BluetoothDevice> pairedDevices =  bt_adapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
    String name = device.getName();
    if (name.contains("K01-Blue")) {
        bt_device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress());
        break;
    }
}
}

//Exit if no Adapter found
if(bt_device == null){ return false; }

//Create Socket         
try {
UUID uuid =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
GlobalVars.bluetooth.bt_socket =GlobalVars.bluetooth.bt_device.createRfcommSocketToServiceRecord(uuid);
    } catch (Exception e) {
    e.printStackTrace();
    }

//Exit if socket not created              
if(bt_socket == null){ return false; }

/Connect to Socket, otherwise exit
try {bt_socket.connect();
    } catch (IOException e1) {return false;}

//get InputStream   
InputStream in = null;
try {in = GlobalVars.bluetooth.bt_socket.getInputStream();
    } catch (IOException e1) {return false;}

//get OutputStream
OutputStream out = null;
try {out = GlobalVars.bluetooth.bt_socket.getOutputStream()
    } catch (IOException e1)  {return false;}

//Say hello to K01 Adapter  
byte[] hello = {0x2F, 0x3F, 0x21, 0x0D, 0x0A};

try {out.write(hello);
   } catch (IOException e1) {return false;}

//Listen to Answer of K01 Adapter
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];

try {
    nRead = in.read(data, 0, data.length);
    while (nRead != -1) {
        nRead = in.read(data, 0, data.length);
        buffer.write(data, 0, nRead);
    }
   } catch (IOException e1) {e1.printStackTrace();}


//Create String from Bytearray
String str1 = new String(buffer.toByteArray());

I Try to connect a Bluetooth Adapter, which send me some Data after sending a Handshake.
My Problem is, until the Adapter is sending, the code works fine, but if it stopped, the in.read(xxx Command blocks whithout any exeption. I have to turne off the adapter and wait severeal seconds, then an exception occurs and the Code resumed.
How to solve this? (I removed the errorhandling for better understanding)

BluetoothAdapter bt_adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bt_device = null;

//Bluetooth not supportet
if (bt_adapter == null) {
    return false;
}

//enable Bluetooth
if (!bt_adapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    return false;
}    

//search K01-Blue Adapter
Set<BluetoothDevice> pairedDevices =  bt_adapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
    String name = device.getName();
    if (name.contains("K01-Blue")) {
        bt_device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress());
        break;
    }
}
}

//Exit if no Adapter found
if(bt_device == null){ return false; }

//Create Socket         
try {
UUID uuid =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
GlobalVars.bluetooth.bt_socket =GlobalVars.bluetooth.bt_device.createRfcommSocketToServiceRecord(uuid);
    } catch (Exception e) {
    e.printStackTrace();
    }

//Exit if socket not created              
if(bt_socket == null){ return false; }

/Connect to Socket, otherwise exit
try {bt_socket.connect();
    } catch (IOException e1) {return false;}

//get InputStream   
InputStream in = null;
try {in = GlobalVars.bluetooth.bt_socket.getInputStream();
    } catch (IOException e1) {return false;}

//get OutputStream
OutputStream out = null;
try {out = GlobalVars.bluetooth.bt_socket.getOutputStream()
    } catch (IOException e1)  {return false;}

//Say hello to K01 Adapter  
byte[] hello = {0x2F, 0x3F, 0x21, 0x0D, 0x0A};

try {out.write(hello);
   } catch (IOException e1) {return false;}

//Listen to Answer of K01 Adapter
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];

try {
    nRead = in.read(data, 0, data.length);
    while (nRead != -1) {
        nRead = in.read(data, 0, data.length);
        buffer.write(data, 0, nRead);
    }
   } catch (IOException e1) {e1.printStackTrace();}


//Create String from Bytearray
String str1 = new String(buffer.toByteArray());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

有木有妳兜一样 2024-10-01 15:50:19

这对我有用:

static ByteArrayOutputStream readbuffer_to()
     {
        ByteArrayOutputStream found = new ByteArrayOutputStream();
        long start = System.currentTimeMillis();
        try {
              if(GlobalVars.bluetooth.in.available() == 0){return found;}
              int nRead = GlobalVars.bluetooth.in.read();
              boolean catched = false;
              while (true) {
                  if(GlobalVars.bluetooth.in.available() > 0)
                  {
                      found.write(nRead);
                      nRead = GlobalVars.bluetooth.in.read(); 
                      start = System.currentTimeMillis();

                  }
                    if(System.currentTimeMillis() - start > 5000) {break;} 

              } 


        } catch (IOException e1) {


        }
         return found;
     }

Thats what worked for me:

static ByteArrayOutputStream readbuffer_to()
     {
        ByteArrayOutputStream found = new ByteArrayOutputStream();
        long start = System.currentTimeMillis();
        try {
              if(GlobalVars.bluetooth.in.available() == 0){return found;}
              int nRead = GlobalVars.bluetooth.in.read();
              boolean catched = false;
              while (true) {
                  if(GlobalVars.bluetooth.in.available() > 0)
                  {
                      found.write(nRead);
                      nRead = GlobalVars.bluetooth.in.read(); 
                      start = System.currentTimeMillis();

                  }
                    if(System.currentTimeMillis() - start > 5000) {break;} 

              } 


        } catch (IOException e1) {


        }
         return found;
     }
独木成林 2024-10-01 15:50:19

“阻塞”不是意味着 in.read() 阻塞线程直到数据来自蓝牙吗?

因此,如果这个侦听器位于自己的线程中,您不需要任何 is.available() 吗?

Isn't that "blocking" means that in.read() is blocking the thread until the data coming from bluetooth?

So if this listener is in own thread you don't need any is.available()?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文