尝试为 Android 应用程序制作光传感器时遇到了一些问题。这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor == null) {
Toast.makeText(MainActivity.this, "No Light Sensor Found! ",
Toast.LENGTH_LONG).show();
} else {
float max = lightSensor.getMaximumRange();
sensorManager.registerListener(this, lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}}
protected void onResume() {
super.onResume();
// register this class as a listener for the lightSensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// called when sensor value have changed
@Override
public void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
float currentLight = event.values[0];
if (currentLight < 1) {
tVCurrentLight.setText("No Light");
} else if (currentLight < 5) {
tVCurrentLight.setText("Dim:"
+ String.valueOf(currentLight));
} else if (currentLight < 10) {
tVCurrentLight.setText("Normal:"
+ String.valueOf(currentLight));
} else if (currentLight < 100) {
tVCurrentLight.setText("Bright(Room):"
+ String.valueOf(currentLight));
} else
tVCurrentLight.setText("Bright(Sun):"
+ String.valueOf(currentLight));
}
}
我遇到的问题是它只能检测到两个状态,即Bright(Room): 10.0和Bright(Sun): 100.0。有什么方法可以修复它,以便它可以显示所有 5 个状态,具体取决于环境?
我在 currentLight 上打印了一个日志,当我用手覆盖屏幕时,我得到的结果只有 10.0,而当我刚刚放在房间里时,我得到的结果是 100.0。任何想法为什么它没有得到其他值?提前致谢。