星期二, 10月 11, 2011

Bluetooth (六)

Android應用程式學習筆記

Managing a Connection

當你已經成功連線兩個或更多裝置,每個裝置都有一個BluetoothSocket。利用BluetoothSocket,輕鬆地通過一般程序傳輸任意數據:

  1. 取得InputStream和OutputStream處理通過Socket的傳輸,分別是getInputStream()和getOutputStream()。
  2. read(byte[])和write(byte[])方法讀或寫數據到資訊流中。
首先,你應該使用專用的執行續處理讀與寫的資訊流。這是非常重要的,因為read(byte[])和write(byte[])是阻絕式呼叫,read(byte[])將會組塞直到有東西從資訊流讀取出,write(byte[])不常阻塞,但是如果遠端裝置不快速呼叫read(byte[])方法及中間的緩衝區滿了就會阻塞,所以在執行續中的主迴圈專用來讀取InputStream,執行續中分開的公開方法可以利用來啟動寫入到OutputStream。

舉例


private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
 
    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
 
        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }
 
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
 
    public void run() {
        byte[] buffer = new byte[1024];  // 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
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
 
    /* Call this from the main Activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }
 
    /* Call this from the main Activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
建構式取得必須的資訊流,一旦執行,執行續等待數據通過InputStream到來,當read(byte[])回傳來自資訊流的byte數據,利用父類別的Handler將數據寄送到主Activity,然後回到執行續中繼續等待更多數據從資訊流送來。

傳送出數據從主Activity呼叫執行續的write()方法,傳入byte數據到方法中,此方法在呼叫write(byte[])將數據傳送到遠端裝置。

執行續的cancel()是重要的,以便通過BluetoothSocket,在任何時間關閉連線,此方法應該在使用完藍芽連線後呼叫。

沒有留言:

張貼留言