我正在开发蓝牙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
做了什么?
我认为并且如评论中所述,它将收到的字节发送到我设置为主要活动的活动。我可以在主Activity中使用Static TextView
而不是sendToTarget()来显示收到的消息吗?
答案 0 :(得分:7)
mHandler
的主要目标是通知您的主要“GUI”主题。在你的情况下是MESSAGE_READ
。
没有处理程序,你可以从主活动线程中做任何事情。
因此,请在主活动中查找mHandler
启动。
默认处理程序init应该是:
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);
我发现here
的来源