6

我是在 android 中使用传感器的新手,现在有点困惑。只有当光线发生明显变化时,我才需要执行一些操作,例如在黑暗的房间里打开灯。到目前为止,我有一个非常简单的默认实现。如何告诉系统我只想对显着的光线变化做出反应?

public class MainActivity extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mLight;
private RelativeLayout mLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    mLayout = (RelativeLayout) findViewById(R.id.mLayout);
    mLayout.setKeepScreenOn(true);
}

@Override
protected void onResume() {
    mSensorManager.registerListener(this, mLight,
            SensorManager.SENSOR_DELAY_FASTEST);
    super.onResume();
}

@Override
protected void onPause() {
    mSensorManager.unregisterListener(this);
    super.onPause();
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    if (sensor.getType() == Sensor.TYPE_LIGHT) {

        // TODO
    }

}

@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_LIGHT) {

        // TODO
    }

  }

}
4

2 回答 2

14

试试下面的代码: -

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView textLIGHT_available, textLIGHT_reading;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textLIGHT_available 
         = (TextView)findViewById(R.id.LIGHT_available);
        textLIGHT_reading 
         = (TextView)findViewById(R.id.LIGHT_reading);

     SensorManager mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

     Sensor lightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
     if(lightSensor != null){
      textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
      mySensorManager.registerListener(
        lightSensorListener, 
        lightSensor, 
        SensorManager.SENSOR_DELAY_NORMAL);

     } else {
      textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
     }
    }

    private final SensorEventListener lightSensorListener
     = new SensorEventListener(){

   @Override
   public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

   }

   @Override
   public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_LIGHT){
     textLIGHT_reading.setText("LIGHT: " + event.values[0]);
    }
   }

    };

}
于 2013-07-01T18:55:50.023 回答
0

如果只是光线变化,您可以检查光线传感器的值是否为 0。如果由于特定原因您检测到一些奇怪的变化,例如 27 到 20,那么我认为您可能必须使用机器学习。

于 2013-11-20T04:09:27.050 回答