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.