Search code examples
javaandroidsensorsandroid-sensors

Light sensors doesn't get values during a loop


My code is this.

public void foo()
    {
            mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
            mSensorManager.registerListener(this, mSensorManager
                    .getDefaultSensor(Sensor.TYPE_LIGHT),
                    SensorManager.SENSOR_DELAY_FASTEST);
             int i=0;
             while(i<10000) //sleep, or something else
                     i++;
             //print the currentLux's value
    }

-

 public void foo()
    {
            new lt().start()
            int i=0;
            while(i<10000) //sleep, or something else
                    i++;
            //print the currentLux's value
    }
class lt extends Thread
{
    public void run()
    {
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mSensorManager.registerListener(this, mSensorManager
                .getDefaultSensor(Sensor.TYPE_LIGHT),
                SensorManager.SENSOR_DELAY_FASTEST);
    }
}

And the sensor event is this:

public final void onSensorChanged(SensorEvent event) 
{
    if( event.sensor.getType() == Sensor.TYPE_LIGHT)
    {
        currentLux+=event.values[0];
    }   
}

This is my problem. I need to create the light sensor and then wait a little (something like 5 seconds) and then check the sum of the values. The problem is that if i use a sleep, a loop or something else, the sensor doesn't get any value. What can i do? Please help me.


Solution

  • I think the problem is that you're pausing the main thread, and that way the onSensorChanged function never called. You should register your listener in onResume, and use Handler.postDelayed(Runnable, long) to execute the display code after the specified delay.