2013-08-03 21 views
6

我正在使用Bluetooth rfcomm連接。 Android示例中有一行我無法理解,但不幸的是,我無法在其他問題和資源中找到好的答案。無法理解Android藍牙示例中的mHandler.obtainMessage()

這裏是整個代碼:

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) { } 
    } 

我無法理解這行:

// Read from the InputStream 
        bytes = mmInStream.read(buffer);  
// Send the obtained bytes to the UI activity 
         mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
           .sendToTarget(); 

mHandler未在此代碼中定義,也MESSAGE_READ

我不能瞭解bytes做什麼?

我認爲,正如評論中提到的那樣,它將收到的字節發送給我設置爲我的主要活動的活動。我可以在主Activity中製作Static TextView而不是sendToTarget()來顯示收到的消息嗎?

+0

mHandler可能是實例變量,在你的類的某個地方聲明。 MESSAGE_READ可能是一個常量,在類中定義或通過靜態導入。 – assylias

回答

7

mHandler的主要目標是通知你的主「GUI」線程。在你的情況下,它的MESSAGE_READ

沒有處理程序,你可以不做任何事情的主要活動線程。

因此,查找mHandler啓動到主Activity中。

默認的處理程序的init應該是這樣的:

Handler mHandler = new Handler(){ 
@Override 
    public void handleMessage(Message msg) { 
/**/ 
    } 
}; 

如果你使用Eclipse,點擊你的項目 - >按Ctrl + H - >文件搜索 - > 「處理程序」。

或者在記事本++ - >產品查詢 - >查找文件....

[編輯]

final int MESSAGE_READ = 9999; // its only identifier to tell to handler what to do with data you passed through. 

// Handler in DataTransferActivity 
public Handler mHandler = new Handler() { 
public void handleMessage(Message msg) { 
    switch (msg.what) { 
    case SOCKET_CONNECTED: { 
     mBluetoothConnection = (ConnectionThread) msg.obj; 
     if (!mServerMode) 
     mBluetoothConnection.write("this is a message".getBytes()); 
     break; 
    } 
    case DATA_RECEIVED: { 
     data = (String) msg.obj; 
     tv.setText(data); 
     if (mServerMode) 
     mBluetoothConnection.write(data.getBytes()); 
    } 
    case MESSAGE_READ: 
     // your code goes here 

我敢肯定,你必須實現這樣的:

new ConnectionThread(mBluetoothSocket, mHandler); 

我發現的消息來源here

+0

謝謝,字節怎麼樣?它有什麼作用? – Bimbow

+0

看我的編輯我張貼 –

+0

嗯,想我應該在這裏寫整個代碼。我會編輯我的問題。 – Bimbow