在我的项目中,我需要使用接近传感器来管理屏幕灯。
从最近3天开始,我正在尝试做同样的事情。但我仍然没有成功。
我的半码工作正常。能够使用接近传感器关闭屏幕灯。但屏幕灯没亮。当我用手盖住传感器时,屏幕灯会亮起。但是在将手从传感器上移开后,光线没有亮起。
我的代码是:
@Override
public void onSensorChanged(SensorEvent event)
{
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY)
{
switch (lastSensorPosition)
{
//case 1 will turn on screen light
case 1:
lastSensorPosition = 2;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL;
getWindow().setAttributes(lp);
break;
//case 2 will turn off screen light
case 2:
lastSensorPosition = 1;
WindowManager.LayoutParams lp1 = getWindow().getAttributes();
lp1.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
getWindow().setAttributes(lp1);
break;
default:
break;
}
}
}
我期待你们的帮助......
答案 0 :(得分:0)
private SensorManager mSensorManager;
private Sensor mSensor;
...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
@Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get an instance of the sensor service, and use that to get an instance of
// a particular sensor.
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
float distance = event.values[0];
// Do something with this sensor data.
}
@Override
protected void onResume() {
// Register a listener for the sensor.
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// Be sure to unregister the sensor when the activity pauses.
super.onPause();
mSensorManager.unregisterListener(this);
}
}
答案 1 :(得分:0)
某些接近传感器返回表示“近”或“远”的二进制值。在这种情况下,传感器通常在远状态报告其最大范围值,在近状态报告较小值。通常,远值是>>的值。 5厘米,但这可能因传感器而异。您可以使用getMaximumRange()方法确定传感器的最大范围。