Android Accelerometer : onSensorChanged Runs Always

天大地大妈咪最大 提交于 2019-12-21 21:19:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!