0

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;

2 Answers2

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.

Vasfed
  • 18,013
  • 10
  • 47
  • 53
-1

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

Vasfed
  • 18,013
  • 10
  • 47
  • 53
  • I am not an expert and therefor I couldn't understand you very well. What do you mean by set the flag to false? And how can I achieve it? – user3882221 Jan 16 '16 at 19:23
  • You're right about "forget to close the tap" concept, but arguments to `bt.sendData` have to little to do with it, since it is being called in an infinite loop – Vasfed Jan 16 '16 at 19:40
  • I think Vasfed have given the same explanation using code and it seems that it would work like a charm – Jawad Hassan Soomro Jan 17 '16 at 21:02