Android的加速度:onSensorChanged一直运行 [英] Android Accelerometer : onSensorChanged Runs Always
问题描述
我已经写在network.It的正常工作,发送UDP消息的方法。
在这之后,我试图用我的Galaxy S smartphone.I的加速计传感器获得的加速度值,显示他们在屏幕上。而当值改变(onSensorChanged方法),我送他们使用UDP到我的计算机上的应用程序。
的问题是,该程序发送该传感器值总是,它们被改变时不。 因此,onSensorChanged方法总是运行。
我把我的手机在桌子上,这些值都在屏幕上不变,但它继续发送。
我怎样才能解决这个问题?
onSensorChanged方式:
公共无效onSensorChanged(SensorEvent事件){
浮动的x,y和z;
如果(event.sensor.getType()== Sensor.TYPE_ACCELEROMETER){
X =(event.values [0]);
Y =(event.values [1]);
Z =(event.values [2]);
outputX.setText(×:+的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));
}
}
发送方式:
公共无效了sendpacket(字符串ipString,INT端口,
字符串消息){
尝试 {
字节[]字节= NULL;
字节= message.getBytes(ASCII);
InetAddress类地址;
尝试 {
地址= InetAddress.getByName(ipString);
}赶上(例外五){
Log.e(错误,异常);
返回;
}
DatagramPacket类包=新的DatagramPacket(字节,bytes.length,
地址,端口);
DatagramSocket的插座=新的DatagramSocket();
socket.send(包);
socket.close();
}赶上(例外五){
Log.e(错误,异常);
返回;
}
}
这可能是最好的保存收到的最后的值只了sendpacket()时,差值大于定义的阈值。
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;
}
}
It is probably best to save the last values received and only sendPacket() when difference is greater than a defined threshold.
这篇关于Android的加速度:onSensorChanged一直运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!