我在Oncreate中设置了两个命令,并且都将数据发送到蓝牙设备。我需要第二个命令来等待从第一个命令接收数据字符串,然后再进入第二个命令。每个命令只向BT发送一个字节。我尝试了一段时间循环true但没有缝合工作并挂起while true语句。我假设while true不会让处理程序在循环中触发。只要我不发送两个命令,两个命令都可以单独工作。
这是Oncreate中的代码,包含两个命令和true语句
looping=true;
intByteCount =9;
GetData(intCommand); // (Command 1)Send byte to get data on reveiver
while( looping) { // Wait add data to be received before next command
Log.d("TAG", "On Hold ? ");
}
intByteCount=160; // (command 2)
GetTitle(intCommand);
这是蓝牙处理程序中的代码,一旦收到所有字节,就会将循环设置为false。
Handler h = new Handler() {
@Override
// public void handleMessage(android.os.Message msg) {
public void handleMessage(android.os.Message msg) {
byte[]readBuf = (byte[]) msg.obj;
if (intByteCount==9){
// Data is channel status and Master value
byte[] encodedBytes = new byte[5];
System.arraycopy(readBuf, 0, encodedBytes, 0, encodedBytes.length);
looping=false;
};
GetTitle和GetData基本相同 这是GetTitle()
private void GetData(int FixtureNumber) {
Log.d("TAG", "Value " + intArrayToInt(intArray1));
intByteCount=9; // set to receive 9 bytes
byte buffer[] = new byte[6];
buffer[0] = ((byte) 1); // Command (get data)
buffer[1] = ((byte) Master_value);
buffer[2] = ((byte) intArrayToInt(intArray1));
buffer[3] = ((byte) intArrayToInt(intArray2));
buffer[4] = ((byte) 3);
buffer[5] = ((byte) 4);
if (isBTConnected) {
try {
mmOutputStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
以下是获取两个控制数据的最终代码
new Thread(new Runnable() {
@Override
public void run() {
intByteCount =9;
GetData(intCommand); // Send byte to get data on reveiver
//you can use a for here and check if the command was executed or just wait and execute the 2nd command
try {
Thread.sleep(1000); //wait 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
intByteCount=160; // Sed incoming data byte count
GetTitle(intCommand);
}
}).start();
答案 0 :(得分:2)
您可以使用线程并等待x个时间,:
new Thread(new Runnable() {
@Override
public void run() {
//your 1st command
//you can use a for here and check if the command was executed or just wait and execute the 2nd command
try {
Thread.sleep(2000); //wait 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
//your 2nd command
}
}).start();
答案 1 :(得分:1)
谢谢你,奥古斯丁工作得很好。收到的数据很快,所以只有延迟才能在没有控制布尔值的情况下工作。这是新代码。
new Thread(new Runnable() {
@Override
public void run() {
intByteCount =9;
GetData(intCommand); // Send byte to get data on reveiver
//you can use a for here and check if the command was executed or just wait and execute the 2nd command
try {
Thread.sleep(1000); //wait 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
intByteCount=160; // Sed incoming data byte count
GetTitle(intCommand);
}
}).start();
答案 2 :(得分:0)
您目前正在举行主线程,不建议这样做。最好的选择是修改代码,以便在使用循环== false
代码的函数中完成第二个蓝牙命令。