Proximity sensor only displaying 2 extreme values

24 Views Asked by At

So I wrote some code that is supposed to continuously output the distance from the phone to whatever object is in front of it by using the proximity sensor. But for some reason whenever I run my application the distance that it displays is always 5 except when I put my finger and completely cover the proximity sensor on my phone(which then it shows 0). No values in between are shown.

I thought I would have the same issue with other sensors but I tested them out and they work perfectly fine, it's just the proximity sensor that does this.

public class MainActivity extends AppCompatActivity implements SensorEventListener{
    TextView sensorStatusTV;
    SensorManager sensorManager;
    Sensor proximitySensor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sensorStatusTV = findViewById(R.id.sensorStatusTV);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
            sensorStatusTV.setText(sensorEvent.values[0] + "");
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }
}
0

There are 0 best solutions below