0
所以基本上,我想从蓝牙流式数据,但开关模式。每个在&关闭模式下发生一段特定的时间,即5秒。 所以, 我需要把一个函数执行5秒,然后在按钮单击方法内执行另一个函数。但我的代码不能正常工作。如何执行特定秒的功能
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn); // button LED ON
btnOff = (Button) findViewById(R.id.btnOff); // button LED OFF
btnStart = (Button) findViewById(R.id.btnStart);
txtArduino = (TextView) findViewById(R.id.txtArduino); // for display the received data from the Arduino
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
btnOff.setEnabled(true);
btnOn.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOn.setEnabled(false);
bluetoothConnect();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOff.setEnabled(false);
bluetoothDisconnect();
}
});
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bluetoothDisconnect();
//Starts from here the code doesn't work
//I want to perform these functions over and over
while (true){
//I want method executed for 5 seconds here
h.postDelayed(new Runnable() {
@Override
public void run(){
bluetoothConnect();
}
}, 5000);
//I want method executed for 5 seconds here
h.postDelayed(new Runnable() {
@Override
public void run(){
bluetoothDisconnect();
}
}, 5000);
}
}
});
}
什么用例为这个?在任何情况下,postDelayed的意思是“在5000毫秒内运行这个代码”,所以它不是你真正想要的。我认为你能做到这一点的唯一方法是使用某种中断。但是,无法保证您通过蓝牙发送的数据在您提供的5秒内能够正确发送,这可能会导致数据损坏问题。 – panini
我把缓冲数据放在一个线程中,所以每次蓝牙套接字都连接数据流。你有什么特定的中断链接,我可以在这里使用? –
我仍然不明白为什么你限制它到5秒运行时间 – panini