问题
I've written a method to send UDP messages over the network.It's working properly.
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.
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 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));
}
}
Send Method :
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;
}
}
回答1:
It is probably best to save the last values received and only sendPacket() when difference is greater than a defined threshold.
来源:https://stackoverflow.com/questions/8528442/android-accelerometer-onsensorchanged-runs-always