Android light sensor not detecting light surrounding properly

484 Views Asked by At

I was having some problem when trying to do a light sensor for Android application. Here is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

    if (lightSensor == null) {
        Toast.makeText(MainActivity.this, "No Light Sensor Found! ",
                Toast.LENGTH_LONG).show();
    } else {
        float max = lightSensor.getMaximumRange();
        sensorManager.registerListener(this, lightSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
    }}

protected void onResume() {
    super.onResume();
    // register this class as a listener for the lightSensor
    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),
            SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
    // unregister listener
    super.onPause();
    sensorManager.unregisterListener(this);
}

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

}

// called when sensor value have changed
@Override
public void onSensorChanged(SensorEvent event) {
    // The light sensor returns a single value.
    // Many sensors return 3 values, one for each axis.
    if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
        float currentLight = event.values[0];
        if (currentLight < 1) {
            tVCurrentLight.setText("No Light");
        } else if (currentLight < 5) {
            tVCurrentLight.setText("Dim:"
                    + String.valueOf(currentLight));
        } else if (currentLight < 10) {
            tVCurrentLight.setText("Normal:"
                    + String.valueOf(currentLight));
        } else if (currentLight < 100) {
            tVCurrentLight.setText("Bright(Room):"
                    + String.valueOf(currentLight));
        } else
            tVCurrentLight.setText("Bright(Sun):"
                    + String.valueOf(currentLight));
    }
}

The problem that I was having was it only able to detect two status which is Bright(Room): 10.0 and Bright(Sun): 100.0. Is there any way to fix it so that it could display all the 5 status depends on the environment?

I printed a Log at the currentLight, the result that I am getting was only 10.0 when covering the scren with hand and 100.0 when I just put in a room. Any ideas why it is not getting other values? Thanks in advance.

0

There are 0 best solutions below