Android编程之光线传感器用法详解

  package com.test.sensor.light;

  import android.app.Activity;

  import android.content.Context;

  import android.hardware.Sensor;

  import android.hardware.SensorEvent;

  import android.hardware.SensorEventListener;

  import android.hardware.SensorManager;

  import android.os.Bundle;

  import android.widget.TextView;

  public class MainActivity extends Activity {

  //感应器管理器

  private SensorManager sensorManager;

  //光线亮度

  private TextView light;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  //当前Activity的内容是一个TextView

  light = new TextView(this);

  setContentView(light);

  //获得感应器服务

  sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

  //获得光线感应器

  Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

  //注册监听器

  sensorManager.registerListener(listener, sensor, SensorManager. SENSOR_DELAY_NORMAL);

  }

  //Activity被销毁

  @Override

  protected void onDestroy() {

  super.onDestroy();

  //注销监听器

  if (sensorManager != null) {

  sensorManager.unregisterListener(listener);

  }

  }

  //感应器事件监听器

  private SensorEventListener listener = new SensorEventListener() {

  //当感应器精度发生变化

  @Override

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  //当传感器监测到的数值发生变化时

  @Override

  public void onSensorChanged(SensorEvent event) {

  // values数组中第一个值就是当前的光照强度

  float value = event.values[0];

  light.setText("当前亮度 " + value + " lx(勒克斯)");

  }

  };

  }