android - Xamarin 蓝牙输入流未读取所有字节(有时)

标签 android xamarin bluetooth xamarin.ios xamarin.forms

我使用此代码读取蓝牙而非 LE 设备的回复。

解决方案是一个 Xamarin Forms 项目,代码位于 DependencyService 中。

using Android.Bluetooth;

....

    public byte[] GetCommand()
    {
        byte[] rbuffer = new byte[200];
        try
        {

            // Read data from the device
            while (!_socket.InputStream.CanRead || !_socket.InputStream.IsDataAvailable())
            {

            }
            int readByte = _socket.InputStream.Read(rbuffer, 0, rbuffer.Length);

        }
        catch (Java.IO.IOException e)
        {

        }
        return rbuffer;
    }

如何解决?

最佳答案

我会使用以下代码:

//create new class for connect thread
  private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;


    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[256];
        int bytes; 

        // Keep looping to listen for received messages
        while (true) {
            try {
                bytes = mmInStream.read(buffer);            //read bytes from input buffer
                String readMessage = new String(buffer, 0, bytes);
                // Send the obtained bytes to the UI Activity via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
    //write method
    public void write(String input) {
        byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
        try {
            mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
        } catch (IOException e) {
            //if you cannot write, close the application
            Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
            finish();

          }
        }
    }

这有助于我从 Arduino 获取蓝牙信息! :)

关于android - Xamarin 蓝牙输入流未读取所有字节(有时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35718125/

相关文章:

android - 多个 APK,仅定位分辨率高于 1280x740 的屏幕

java - 将多个 ViewHolder 与 RecyclerView 一起使用

xamarin - IOS 应用程序崩溃,甚至没有输入我的代码

iphone - iOS 蓝牙数据传输、Gamekit 或 Bonjour

python - 在 python 中将蓝牙设备与密码/密码配对 - RFCOMM (Linux)

android - 如何制作可滚动的 TableLayout?

Android:听所有 toast

Android:无法在防火墙后面进行 httprequest

ios - 在 Xamarin.Forms 中检查用户使用的是 iPhone 还是 iPad

node.js - 让 Electron 与 Node 的蓝牙串行端口一起工作