Android 加速度计:onSensorChanged 始终运行 [英] Android Accelerometer : onSensorChanged Runs Always
问题描述
我已经编写了一种通过网络发送 UDP 消息的方法.它工作正常.
I've written a method to send UDP messages over the network.It's working properly.
在那之后,我尝试使用我的 Galaxy S 智能手机的加速度计传感器.我得到了加速度计的值,并将它们显示在屏幕上.当值发生变化时(onSensorChanged 方法),我使用 UDP 将它们发送到我计算机上的应用程序.
After that, i tried to use the Accelerometer Sensor of my Galaxy S smartphone.I get the accelerometer values, show them in the screen. And when the values are changed(onSensorChanged method) , i send them using UDP to the application on my computer.
问题在于程序总是发送传感器值,而不是在更改时发送.所以,onSensorChanged 方法一直在运行.
The problem is that the program sends the sensor values always, not when they are changed. So, the onSensorChanged method is running always.
我把手机放在桌子上,屏幕上的值是恒定的,但它会继续发送.
I put my phone on the desk, the values are constant in the screen but it continues to send.
我该如何解决这个问题?
How can i fix this ?
onSensorChanged 方法:
onSensorChanged method :
public void onSensorChanged(SensorEvent event) {
float x,y,z;
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
x=(event.values[0]);
y=(event.values[1]);
z=(event.values[2]);
outputX.setText("x:"+String.format("%.1f",x));
outputY.setText("y:"+String.format("%.1f",y));
outputZ.setText("z:"+String.format("%.1f",z));
sendPacket("192.168.2.40", 10001,
"X:" +String.format("%.1f",x) +
"Y:" +String.format("%.1f",y) +
"Z:" +String.format("%.1f",z));
}
}
发送方法:
public void sendPacket( String ipString, int port,
String message) {
try {
byte[] bytes = null;
bytes = message.getBytes("ASCII");
InetAddress address;
try {
address = InetAddress.getByName(ipString);
} catch (Exception e) {
Log.e("Error","Exception");
return;
}
DatagramPacket packet = new DatagramPacket(bytes, bytes.length,
address, port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
} catch (Exception e) {
Log.e("Error","Exception");
return;
}
}
推荐答案
最好保存最后接收到的值,并且只有当差异大于定义的阈值时才使用 sendPacket().
It is probably best to save the last values received and only sendPacket() when difference is greater than a defined threshold.
这篇关于Android 加速度计:onSensorChanged 始终运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!