public class MainActivity extends AppCompatActivity implements SensorEventListener{
private TextView tv_content;
private Sensor sensor_light;
private SensorManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_content= (TextView) findViewById(R.id.tv_content);
manager= (SensorManager) getSystemService(SENSOR_SERVICE);
sensor_light= manager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
/**
* ③
* onResume()中注册传感器,先让主函数实现SensorEventListener接口,重写里边两个方法
* SensorManager.SENSOR_DELAY_NORMAL表示刷新频率是正常频率
*/
@Override
protected void onResume() {
super.onResume();
manager.registerListener(this,sensor_light,SensorManager.SENSOR_DELAY_NORMAL);
}
/**
* ④
* onPause()中解除注册
*/
@Override
protected void onPause() {
super.onPause();
manager.unregisterListener(this);
}
/**
* ⑤ 重写SensorEventListener接口中的两个方法
* onSensorChanged是指传感器中数据发生改变
* onAccuracyChanged是指精度改变,此处用不到略过
* values[0]就是指光线传感器中的具体数值
* @param event
*/
@Override
public void onSensorChanged(SensorEvent event) {
float[] values= event.values;
switch (event.sensor.getType()){
case Sensor.TYPE_LIGHT:
tv_content.setText("当前屏幕亮度: "+values[0]);
break;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}