1

I am trying to make an Android App where the application will send data through bluetooth to the bluetooth module (HC-05)when the user taps on the button(keep holding it) and when the user releases the button, the other data should be send to stop the car. I've tried to do it with the following code but it is not working properly:

forwardButton.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                sendData("F");
                return false;
            }

            if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                sendData("S");
                return true;
            }
            return true;
        }
    });

//This method is to send data
public void sendData(String data){
    if(mBTSocket != null){
        try{
            mBTSocket.getOutputStream().write(data.getBytes());
            Toast.makeText(getApplicationContext(), "Sent data " + data, Toast.LENGTH_SHORT).show();
        }
        catch (IOException io){
            Toast.makeText(getApplicationContext(),"Unable to send data",Toast.LENGTH_SHORT).show();
        }
    }
}

I'm using Arduino on the other side along with bluetooth module to receive data and for processing.
But the above code isn't working properly, sometimes it starts moving and doesn't stops on releasing the button.
By the way these methods are inside the onCreate() method of the MainActivity.
Plz help, what I'm doing wrong in the code.

Irfan Ansari
  • 73
  • 2
  • 9
  • Hi. I think this describes the problem you are having. http://stackoverflow.com/questions/15799839/motionevent-action-up-not-called .. to fix it you need to `return true` from `ACTION_DOWN` (consuming the event) or `ACTION_UP` will never be triggered. – trooper Mar 14 '17 at 17:37
  • Possible duplicate of [MotionEvent.ACTION\_UP not called](http://stackoverflow.com/questions/15799839/motionevent-action-up-not-called) – trooper Mar 14 '17 at 17:37
  • I tried it but still it's not working (but yeah atleast now ACTION_UP event has performed). However , the car is still sometimes moving and sometimes doesn't. Do I need to remove `return true` statement from `ACTION_UP`? – Irfan Ansari Mar 14 '17 at 18:02

0 Answers0