1.布局
放置一个TextView,用于显示当前光照强度。
<TextView
android:id="@+id/tv_light_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26sp"/>
2.activity
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv_light_level)
TextView tvLightLevel;
private SensorManager sensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
//values数组中第一个下标的值就是当前的光照强度
float value = event.values[0];
tvLightLevel.setText("当前光照强度:" + value + "lx");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if(sensorManager != null){
sensorManager.unregisterListener(listener);
}
}
}