简体   繁体   中英

How to slow the rate at which light sensor listens?

I want to limit the frequency at which light sensor detects light, to save battery power and CPU usage.

After reading SO as well as trying it myself, I've found that changing the parameters of the registerListener method does nothing.

So next bet I guess is to make it sleep or wait every time the sensor senses light? How would I do that? I tried just putting wait(2000); inside it but that gives an error.

Here's the light sensor code:

SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);

Sensor light = sm.getDefaultSensor(Sensor.TYPE_LIGHT);

SensorEventListener listener = new SensorEventListener() {

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

          @Override
          public void onSensorChanged(SensorEvent event) {
                //Here is where I want to do my stuff   
          }

};

sm.registerListener(listener, light, SensorManager.SENSOR_DELAY_NORMAL);

Do your stuff at minimum interval:

    private final long minimumInterval = 100;
    private long lastRefresh;

    SensorEventListener listener = new SensorEventListener() {

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

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            long timeMillis = System.currentTimeMillis();
            if (lastRefresh - timeMillis > minimumInterval) {
                lastRefresh = timeMillis;
                //do stuff
            }
        }

    };

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