我目前正在开发一款通过蓝牙与专有设备进行通信的应用。 通过探索Bluetooth Chat Example,我可以完美地完成沟通。 在此示例中,整个写入/读取过程如下: https://goo.gl/photos/3CoSNbhRtyDNoV1F6
现在我想从MyBluetoothClass内部创建一个写/读方法(用于校验和验证)。所以它会是这样的: //见上面的相同链接//
但是现在该方法除了写入和读取本身之外还执行所有操作,在方法完成后才会发生。 有人可以给我一个关于如何进行的建议吗?以下是与新写作方法相关的方法。
//Writing method called from the Activity
private String writeWithChksum(String msg) {
write(msg);
readCompleted.set(false);
return processDeviceID();
}
//Get the device ID
private String processDeviceID() {
Thread timeoutThread;
int tries = 0;
while(tries < 3) {
tries++;
System.out.println("Trying to get ID for the "+tries+" time.");
waitingMessage.set(true);
timeout.set(false);
timeoutThread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(TIME_LIMIT);
timeout.set(true);
} catch (InterruptedException e) {
}
}
};
timeoutThread.start();
while(waitingMessage.get() && !timeout.get()) {
sleepThread(150);
}
timeoutThread.interrupt();
}
readCompleted.set(true);
return deviceID;
}
//Handler used to deal with BT methods
private final Handler auxHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothSerial.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
//THIS SHOULD APPEAR IN EXECUTION TIME WHILE THE INITIAL METHOD IS STILL RUNNING, NOT AFTER
Log.d(TAG,"BLUETOOTH_HANDLER -->" + "Wrote: "+writeMessage);
break;
case BluetoothSerial.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
//THIS AS WELL NEED TO APPEAR WHILE IN EXECUTION TIME
Log.d(TAG,"BLUETOOTH_HANDLER -->" + "Read: "+readMessage);
System.out.println("Gonna process the message");
processMessage(readMessage);
break;
}
}
};
//Standard writing method
public void write(String msg) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
msg = ">"+msg+"<\r\n";
byte[] send = msg.getBytes();
r.write(send);
msgNumber++;
sleepThread(400);
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}