Dolphy the Reaper
Dolphy the Reaper

Reputation: 75

Proximity sensor on android gives data too many times

I'm creating a simple application on Android and I was reading about sensors. 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) 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. 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.

Upvotes: 1

Views: 276

Answers (1)

programmer
programmer

Reputation: 36

Try setting a bool named hasDisplayedToast and set it to true once the operation has completed. 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. I'm not too familar with that language but it seems similar to 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;
            } 
        }
    }

Upvotes: 2

Related Questions