我试图在按钮被按下时通过蓝牙连续发送数据,直到它被释放,但在我的代码中,我只在按钮被按下或释放时接收一次数据。
在这里,我使用了 OnTouchListener
与 Action_Down and Action_Up
.如果有人能帮助我,那将是非常伟大的,谢谢你。
fab1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
TextView d;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:data[0]='H';
if(connection_check)
{
d =findViewById(R.id.datacheck);
String str=String.valueOf(data)+"\n";
d.setText(str);
sendData.write(str.getBytes());
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
break;
case MotionEvent.ACTION_UP:
data[0]='L';
if(connection_check)
{
d =findViewById(R.id.datacheck);
String str=String.valueOf(data)+"\n";
d.setText(str);
sendData.write(str.getBytes());
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
break;
}
你下面的代码发送数据将只在用户按下按钮时被调用一次。
data[0]='H';
if(connection_check)
{
d =findViewById(R.id.datacheck);
String str=String.valueOf(data)+"\n";
d.setText(str);
sendData.write(str.getBytes());
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
你需要创建一个处理程序和Runnable来连续调用你的发送函数,并根据按钮事件来启动和停止它。
Runnable:
Runnable dataSender = new Runnable(){
@override
void run(){
if(isPressed && connection_check)
{
d =findViewById(R.id.datacheck);
String str=String.valueOf(data)+"\n";
d.setText(str);
sendData.write(str.getBytes());
handler.postDelayed(this,100) // for 100 milliseconds
}
else
return
}
}
Handler:
Handler handler = new Handler(Looper.getMainLooper())
现在创建一个全局布尔变量isPressed,并将其设置为false。现在在你的onTouchListener中相应地设置isPressed,并使用handler启动runnable。
fab1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
TextView d;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
isPressed = true
handler.post(dataSender) // start the handler
break;
case MotionEvent.ACTION_UP:
isPressed = false //to stop the handler
data[0]='L';
if(connection_check)
{
d =findViewById(R.id.datacheck);
String str=String.valueOf(data)+"\n";
d.setText(str);
sendData.write(str.getBytes());
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
break;
}