简体   繁体   中英

Proximity Sensor Counter gives double value in android

I am trying to make a counter that counts how many times the proximity sensor is triggered in Android.

But the problem that I am facing is, the counter counts twice every time the proximity sensor is triggered.

First, for the entry time and second for the exit time.

The code that I have so far is

public void onSensorChanged(SensorEvent event) {
         textView1 = (TextView) findViewById(R.id.textView2);
      if (event.values[0] == 0) {

      } else {
       counter++;
       textView1.setText(""+counter);

      }
     }

For instance if the sensor is triggered the counter variable returns value of 2, how do I correct it?

Any help is appreciated.

Please note that sensor is triggered when something is close to it (eg hand, face, any object) and when you move object away. It means, when you put your hand close to the sensor and immediately move it away, sensor will be triggered two times. Sensor should give you two values: one for the situation, when object is close to the sensor and another one when nothing is close to the sensor. One of the values from the SensorEvent changes. I don't remember which one. You should check, which value changes and what are sensor readings for situation when object is close and when there's no object. After that, you can use this value inside the conditional "if" statement depending on the fact which moment you want to detect (object is moved close to sensor or object is moved away from the sensor).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM