先在布局中建立一个TextView, 用于测试当前的光照强度:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/light_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp" />
</RelativeLayout>
在Activity 中要进行以下几步操作:
1. 获取SensorManager 和Sensor 实例
private SensorManager sensorManager;
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
2. 通过SensorEventListener 对传感器进行监听:
private SensorEventListener listener