2013-07-14 45 views
2

我想了解這段代碼: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; 
       } 
      } 
     } 

和唯一的事情,完全不起眼對我來說是obtainMessage(MESSAGE_READ, bytes, -1, buffer),其對應於下一個聲明:

public final Message obtainMessage (int what, int arg1, int arg2, Object obj) 

Added in API level 1 
Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message. 

Parameters 
what Value to assign to the returned Message.what field. 
arg1 Value to assign to the returned Message.arg1 field. 
arg2 Value to assign to the returned Message.arg2 field. 
obj  Value to assign to the returned Message.obj field. 

所以請,有人可以向我解釋這些參數是什麼以及他們服務的是什麼?

P.S .: MESSAGE_READ在該代碼中未定義。

回答

3
mHandler.obtainMessage(): 

通過使用這種方法,我們允許Android採取集中Message對象,這有助於保持對象分配下來的照顧,尤其是如果你正在創建的消息頻繁,如使用處理程序動畫。

what:用戶定義的消息代碼,以便收件人可以識別此消息的內容。

obj要發送給收件人的任意對象。

如果您只需要存儲幾個整數值,arg1和arg2是使用setData()的低成本替代方案。

+0

以及如果我想存儲更多整數 –

0

它們都由您定義。什麼是ID。它通常是一個枚舉或常量定義在擁有您將它發佈到的處理程序的類中。它應該定義消息的類型,假設有多個消息要發送。 arg1,arg2和obj都是與消息一起發送的值,以防您需要傳遞數據。他們可以擁有任何你想要的價值,或者根本沒有價值。