简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM