簡體   English   中英

Android藍牙讀取InputStream

[英]Android Bluetooth Read InputStream

我正在嘗試讀取從外部藍牙模塊發送到我的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());
}

}

InputStream.read()方法是阻塞的,這意味着它會阻塞你的代碼,直到一些數據到達,或者某些東西破壞管道(如斷開主機或關閉流)。 阻塞是CPU友好的,因為線程處於WAIT狀態(休眠),直到中斷使其處於READY狀態,因此它將被安排在CPU上運行; 所以你在等待數據時WONT使用cpu,這意味着你將使用更少的電池(或者你將CPU時間留給其他人的線程)!

available()給出了實際可用的數據,並且因為串行通信非常慢(11n00波特在8n1意味着11520字節/秒)並且你的循環運行速度至少快一到兩個數量級,你會讀到很多0,並且使用大量的cpu來要求零......這意味着你要使用大量的電池。

循環可用在arduino上不是問題,因為你只有一個線程/進程:你的代碼。 但是在多線程系統中循環檢查數據(稱為“輪詢”)總是一個壞主意,並且只有在你沒有其他選擇時才應該完成,並且總是添加一點sleep()以便你的代碼贏得' t竊取CPU到系統和其他線程。 好主意是使用阻塞調用(對於初學者來說很容易使用)或者像你對圖形事件那樣使用事件系統(並不總是被你使用的庫支持,並且需要同步,所以它很棘手,但你不會產生其他線程你自己的代碼,但請記住,串行和圖形的數據和你的應用程序PROBABLY在不同的線程中,應該同步)

您正在使用

import java.util.logging.Handler;

將其更改為

import android.os.Handler;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM