Android light sensor - detect significant light changes

穿精又带淫゛_ 提交于 2019-11-30 10:06:23
Yogesh Tatwal

try the below code :-

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView textLIGHT_available, textLIGHT_reading;

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

        textLIGHT_available 
         = (TextView)findViewById(R.id.LIGHT_available);
        textLIGHT_reading 
         = (TextView)findViewById(R.id.LIGHT_reading);

     SensorManager mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

     Sensor lightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
     if(lightSensor != null){
      textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
      mySensorManager.registerListener(
        lightSensorListener, 
        lightSensor, 
        SensorManager.SENSOR_DELAY_NORMAL);

     } else {
      textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
     }
    }

    private final SensorEventListener lightSensorListener
     = new SensorEventListener(){

   @Override
   public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

   }

   @Override
   public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_LIGHT){
     textLIGHT_reading.setText("LIGHT: " + event.values[0]);
    }
   }

    };

}

If there was just a light change you can just check to see if the light sensor value is 0. If you're detecting some weird change like 27 to 20 for a specific reason, then I think you might have to use machine learning.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!