问题
I want to send data to an arduino mega 2560 as long as a button is being pressed and when that button is released it will stop sending informations. I am using onTouchListener with MotionEvent constants. But when I run this on my phone I press the button and it sends data even though after a while I release it. Where am I being wrong here?
switch (v.getId()) {
case R.id.left1: // check what button is pressed
while(event.getAction() == MotionEvent.ACTION_DOWN) {
bt.sendData("1"); // while pressing the button it sends data
}
if(event.getAction() == MotionEvent.ACTION_UP) {
// when it stops, do nothing
}
break;
}
return true;
回答1:
Your problem is in infinite loop while(event.getAction() == MotionEvent.ACTION_DOWN)
that you start upon receiving the first event.
OnTouchListener
is called for each event that is dispatched to view, down and up are separate events and event does not change while being processed.
So to solve your problem - you need to send data from a separate thread.
Start it on ACTION_DOWN
and also have a flag that will be modified on ACTION_UP
to indicate thread to exit.
回答2:
You have to set the flag of bt.sendData
to false
when button is released which seems to be absent in your code.
It's like you open tap for water but forget to close the tap when you are finished. Hope it helps
来源:https://stackoverflow.com/questions/34830916/send-data-to-arduino-as-long-as-the-button-is-being-pressed