1

在我的项目中,我需要使用接近传感器来管理屏幕光。

从过去 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;
        }
    }
}

我期待着你们的大力帮助...

4

2 回答 2

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);
      }
    }
于 2013-08-02T09:24:03.537 回答
0

一些接近传感器返回表示“近”或“远”的二进制值。在这种情况下,传感器通常在远状态报告其最大范围值,在近状态报告其较小的值。通常,远值是 > 5 cm 的值,但这可能因传感器而异。您可以使用 getMaximumRange() 方法确定传感器的最大范围。

于 2013-08-02T09:38:05.807 回答