Search code examples
androidproximitysensor

Proximity Sensor and onSensorChanged


I am making an application for which I want a number counting as something is near the proximity sensor, like if I place my finger on sensor it displays 1 on textview, if I do it again it displays 2 and so on. I am not able to figure out what condition to use on onSensorChanged.

public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    try{
        if(event.values[0] < event.sensor.getMaximumRange()){
            for (i=(int) event.values[0];i<=100;i++)
            Toast.makeText(getApplicationContext(), "" +i, Toast.LENGTH_LONG).show();

            tv.setText(i);

        }


    }catch(Exception e){
        e.printStackTrace();
    }
}

I cannot get the values in textview and in toast the values are keeping on incrementing


Solution

  • Try this...

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.values[0] < event.sensor.getMaximumRange()) {
            // Object is near to the Sensor. increment the value
        }
    }
    

    and according to your code

    private int nearCount; // global variable.
    
     @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.values[0] < event.sensor.getMaximumRange()) {
            nearCount++;
            Toast.makeText(getApplicationContext(), "Count = "+nearCount, Toast.LENGTH_SHORT).show();
        }
    }