简体   繁体   English

android 上的接近传感器提供数据的次数过多

[英]Proximity sensor on android gives data too many times

I'm creating a simple application on Android and I was reading about sensors.我正在 Android 上创建一个简单的应用程序,并且正在阅读有关传感器的信息。 Right now, I'm using a proximity sensor to display a simple toast.现在,我正在使用接近传感器来显示一个简单的吐司。 When I wave the hand above the phone, the sensor should display a toast with a simple message given by me.当我在手机上方挥手时,传感器应该会显示一个带有我给出的简单信息的祝酒词。 Well, it does that, but it displays the toast too many times.好吧,它确实这样做了,但是它显示吐司的次数太多了。
This is the code I'm using:这是我正在使用的代码:

    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
            if(event.values[0] == 0) {
                Toast.makeText(appCompatActivity.getApplicationContext(), "near", Toast.LENGTH_SHORT).show();
            } 
        }
    }

And for getting the SensorManager:对于获取 SensorManager:

      SensorManager sensorManager = (SensorManager) appCompatActivity.getSystemService(Context.SENSOR_SERVICE);
      Sensor proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
      sensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_FASTEST);

That parameter, SensorManager.SENSOR_DELAY_FASTEST was changed from SENSOR_DELAY_NORMAL but the speed it's the same.该参数 SensorManager.SENSOR_DELAY_FASTEST 已从 SENSOR_DELAY_NORMAL 更改,但速度相同。 I feel that some kind of buffering happens behind, but I do not manage to get that.我觉得后面发生了某种缓冲,但我没能做到。 I want when hovering the hand, the toast to appear just once until I will hover again.我想当手悬停时,吐司只出现一次,直到我再次 hover。

Try setting a bool named hasDisplayedToast and set it to true once the operation has completed.尝试设置一个名为 hasDisplayedToast 的布尔值,并在操作完成后将其设置为 true。 That will make it only happen once.这将使它只发生一次。 If you want the operation to continually occur, you can set a timer and set the bool to false after a while.如果您希望操作持续发生,您可以设置一个计时器并在一段时间后将 bool 设置为 false。 I'm not too familar with that language but it seems similar to C++我对那种语言不太熟悉,但它似乎类似于 C++

 bool hasDisplayedToast = false;
 public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
            if(event.values[0] == 0 && !hasDisplayedToast) {
                Toast.makeText(appCompatActivity.getApplicationContext(), "near", Toast.LENGTH_SHORT).show();
                hasDisplayedToast = true;
            } 
        }
    }

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

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