Android光线传感器-android学习之旅(65)

主要讲解光线传感器的使用,其实所有的传感器用法类似

主要是定义一个TextView用来显示光线强度,用完了以后记得在OnDestory里面释放资源

代码如下

public class MainActivity extends Activity {
    private SensorManager sensorManager;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        sensorManager.registerListener(sensorEventListener,sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }
    private SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            float value = sensorEvent.values[0];
            textView.setText("光线强度是"+value+"勒克斯");
        }

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

        }
    };
    @Override
    protected void onDestroy() {
        if (sensorManager != null){
            sensorManager.unregisterListener(sensorEventListener);
        }
        super.onDestroy();
    }

你可能感兴趣的:(移动开发,javascript)