我正在尝试从非 Android 蓝牙设备(带有 HC-06 的 arduino)接收数据(字符串)。 arduino 内部的代码看起来相当不错,它在连续循环中发送一个字符串,我能够使用串行监视器看到它。 但是当我尝试将它与我的 Android 手机一起使用时,它会配对、连接并在 toast 中显示“连接”,但我始终无法接收其字符串并将其显示在 TextView 上。请告诉我我是否做错了什么。
我的 Activity 类中 onCreate 方法中的代码:
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what)
{
case SUCCESS_CONNECT:
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connect", 0).show()
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, 0).show();
tvTest.setText(string);
ConnectedThread 类内部:
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
最佳答案
我可以通过调用来解决这个问题
connectedThread.start();
之后,
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
SUCCESS_CONNECT 情况下的行。
关于java - Android 蓝牙已配对、连接但从未将数据接收到 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568499/