6

我正在处理蓝牙 rfcomm 连接。Android Sample 中有一行我无法理解,不幸的是我在其他问题和资源中找不到好的答案。

这是整个代码:

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做什么的?

我认为,正如评论中提到的,它将接收到的字节发送到我设置为主要活动的活动。我可以Static TextView在我的主 Activity 中创建一个而不是 sendToTarget() 来显示收到的消息吗?

4

1 回答 1

7

的主要目标Handler是提供生产者和消费者线程之间的接口,这里是 UI 线程和工作线程之间的接口。实施Handler进入消费者线程。

在您的情况下,您希望MESSAGE_READ在线程之间进行通信。

如果没有处理程序,您将无法从主活动线程中执行任何操作。

因此,寻找mHandler进入主要活动的开始。

默认处理程序初始化应该是这样的:

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

如果您使用 Eclipse,请单击您的项目 -> Ctrl+H -> 文件搜索 -> “处理程序”。

或在 Notepad++ -> Serch -> 在文件中查找 ....

[编辑]

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);

我在这里找到的来源

于 2013-08-03T09:01:24.340 回答