安卓蓝牙读取输入流

5
我试图读取外部蓝牙模块发送到我的HTC Sensation的串行数据。但是当我调用InputStream.available()时,它返回0,因此我不能遍历接收到的字节并调用InputStream.read(byteArray)。
请问有人能帮我解决这个问题吗?
在读取字节之前,我需要检查可用的字节数吗?
对于我不准确的技术帖子,我深表歉意。
以下是我的代码:
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());
}

}


只需在读取方法中将其删除并阻止它。目前,每当available()为零时,您只是在消耗CPU并不经意地耗尽电池,而这在任何平台上大多数时间都是如此。 - user207421
我不明白你的意思。 - user3066347
2个回答

7

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

available()提供实际可用的数据,因为串行通信非常缓慢(115200波特率在8n1下意味着每秒11520字节),而您的循环至少运行一到两个数量级更快,所以您将读取很多0,并使用大量CPU来请求那个零...这意味着您会使用很多电池。

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


0

您正在使用

import java.util.logging.Handler;

将其更改为

import android.os.Handler;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接