Android接近传感器给出错误的结果

时间:2013-01-14 12:24:32

标签: android-sensors proximity

首先发布这里,但stackoverflow解决了很多问题。不过这一点,我似乎无法搞清楚。我正在创建一个Android应用程序,每次接近检测时,它会递增,TextView值减1。出于某种原因,当活动开始或恢复(电源按钮)时,它记录2次接近命中。我已经仔细检查以确保在按下电源按钮时我不能靠近探测器。

以下是代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.exercise);
    //start proximity
    startProximitySensor(sensorListener());
}

private SensorEventListener sensorListener(){
    listener = new SensorEventListener(){

        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onSensorChanged(SensorEvent event) {
            if(event.sensor.getType() == Sensor.TYPE_PROXIMITY){
                String maxRange = String.valueOf(mProximitySensor.getMaximumRange());
                if(event.values[0] == Float.parseFloat(maxRange)){
                    updateTextView();
                    Log.i(TAG,"Proximity Sensor Reading: "+ String.valueOf(event.values[0]));


                }

            }

        }

    };

    return listener;
}

private void startProximitySensor(SensorEventListener proximitySensorEventListener){
    mSensorManager = (SensorManager)getSystemService(getApplicationContext().SENSOR_SERVICE);
    mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    if(mProximitySensor == null){
        Log.i(TAG,"No proximity sensor found!");
    }else{
        proximityStarted = true;
        Log.i(TAG,"Proximity started");
        mSensorManager.registerListener(proximitySensorEventListener,mProximitySensor,SensorManager.SENSOR_DELAY_UI);
    }
}

我设法通过在onResume中创建timeStamp并将其与每个传感器更改时生成的SystemTime进行比较来解决这个问题。如果它们的差异小于1秒,则TextView将不会更新。这有效,但我仍然想知道我是否遗漏了什么。

提前致谢

0 个答案:

没有答案