java - Android 蓝牙读取输入流

标签 java android bluetooth arduino

我正在尝试读取从外部蓝牙模块发送到我的 HTC Sensation 的串行数据,但是当我调用 InputStream.available() 时 - 它返回 0,因此我无法遍历接收到的字节并调用 InputStream.read(字节数组)。

有人可以帮我解决这个问题吗?

我需要在读取之前检查可用字节吗?

对于我在技术上不准确的帖子,我深表歉意。

这是我的代码:

public class BluetoothTest extends Activity
{
TextView myLabel;
TextView snapText;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button openButton = (Button)findViewById(R.id.open);
    Button closeButton = (Button)findViewById(R.id.close);

    Button chkCommsButton  = (Button)findViewById(R.id.chkCommsButton);
    Button offButton = (Button)findViewById(R.id.offButton);

    myLabel = (TextView)findViewById(R.id.mylabel);
    snapText = (TextView)findViewById(R.id.snapText);


    //Open Bluetooth
    openButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                findBT();
                openBT();
            }
            catch (IOException ex) { }
        }
    });

    //Close Bluetooth
    closeButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                closeBT();
            }
            catch (IOException ex) { }
        }
    });


    // Check Comms     - multicast all SNAP nodes and pulse their  BLUE led
     chkCommsButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                chkcommsButton();
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    });

  //Off Button    - set strip to all OFF
    offButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                offButton();
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    });


}


void findBT()
{
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null)
    {
        myLabel.setText("No bluetooth adapter available");
    }

    if(!mBluetoothAdapter.isEnabled())
    {
        Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
        for(BluetoothDevice device : pairedDevices)
        {
            if(device.getName().equals("BTNODE25"))    // Change to match RN42 - node name
            {
                mmDevice = device;
                Log.d("ArduinoBT", "findBT found device named " + mmDevice.getName());
                Log.d("ArduinoBT", "device address is " + mmDevice.getAddress());
                break;
            }
        }
    }
    myLabel.setText("Bluetooth Device Found");
}

void openBT() throws IOException
{
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);        
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();

    beginListenForData();

    myLabel.setText("BT  << " + mmDevice.getName()  + " >> is now open ");
}

void closeBT() throws IOException
{
    stopWorker = true;
    mmOutputStream.close();
    mmInputStream.close();
    mmSocket.close();
    myLabel.setText("Bluetooth Closed");
}

void beginListenForData()
{
    final Handler handler = new Handler(); 
    final byte delimiter = 10; //This is the ASCII code for a newline character

    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable()
    {
        public void run()
        {                
           while(!Thread.currentThread().isInterrupted() && !stopWorker)
           {
                try 
                {

                    int bytesAvailable = mmInputStream.available();  
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInputStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++)
                        {
                            byte b = packetBytes[i];
                            if(b == delimiter)
                            {
                                byte[] encodedBytes = new byte[readBufferPosition];
                                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                final String data = new String(encodedBytes, "US-ASCII");
                                readBufferPosition = 0;

                                handler.post(new Runnable()
                                {
                                    public void run()
                                     {
                                        snapText.setText(data);
                                     }
                                });
                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                } 
                catch (IOException ex) 
                {
                    stopWorker = true;
                }
           }
        }
    });

    workerThread.start();
}


  void offButton() throws IOException
{
    mmOutputStream.write("0".getBytes());
}


void chkcommsButton() throws IOException
{
    mmOutputStream.write("1".getBytes());
}

最佳答案

InputStream.read() 方法是阻塞的,这意味着它将阻塞您的代码,直到某些数据到达,或者某些东西破坏了管道(例如主机断开连接或关闭流)。 阻塞是 CPU 友好的,因为线程处于 WAIT 状态( sleep )直到中断将其置于 READY 状态,因此它将被安排在 CPU 上运行;所以你不会在等待数据时使用 cpu,这意味着你会使用更少的电池(或者你将 CPU 时间留给其他线程)!

available() 给出了实际可用的数据,因为串行通信真的很慢(115200 波特在 8n1 意味着 11520 字节/秒)并且你的循环运行速度至少快一到两个数量级,您将读取很多 0,并使用大量 cpu 来请求该零...这意味着您使用了大量电池。

可用循环在 arduino 上不是问题,因为您只有一个线程/进程:您的代码。但是在多线程系统中循环检查数据(称为“轮询”)总是一个坏主意,只有在您别无选择时才应该这样做,并且总是添加一点 sleep() 这样您的代码就不会t 窃取 CPU 给系统和其他线程。好主意是使用阻塞调用(对于初学者来说很容易使用)或像你为图形事件所做的那样的事件系统(你使用的库并不总是支持它,并且需要同步,所以它很棘手但你不会在其中产生其他线程你自己的代码,但请记住,来自串行和图形的数据以及你的应用程序可能在不同的线程中,并且应该同步)

关于java - Android 蓝牙读取输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22846076/

相关文章:

java - 使用 Spring boot 的 SOAP 和 Rest Web 服务

java - 访问 WebContent 文件夹下子文件夹中的 JSP 页面

android - 有没有类似Android中带有verticalSeekBar控件的SeekBar的onStopTrackingTouch的功能?

android - FusedLocationApi.getLastLocation 返回 null

android - 在 Android 中打开/关闭蓝牙

android - 在我的一个蓝牙类(class)中遇到一个奇怪的 NPE,以前没有发生过

java - 如何在HBase中实现分页?

java - 如何在tr td中定位表中的元素

android - 来自服务器的 API 调用需要一个 appsecret_proof 参数

ios - 使用 Swift 通过蓝牙发送消息