简体   繁体   English

接近传感器计数器在android中提供双值

[英]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. 我正在尝试创建一个计数器,该计数器计算在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? 例如,如果传感器被触发,则计数器变量返回值2,我该如何纠正?

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. SensorEvent的值SensorEvent更改。 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). 之后,您可以根据要检测的时刻(对象移近传感器或对象移离传感器)在条件“ if”语句中使用此值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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