我有一个LightSensor广播变化。基本上即使没有从0变化,它也会在每次采样时进行广播。我应该如何让传感器基本上仅广播ON / OFF值。例如,如果lux> 0然后灯亮,否则lux = 0,因此灯灭。
sendLuxUpdate():
public class LightSensor extends Service implements SensorEventListener {
private SensorManager mSensorManager;
public Sensor LightSensor;
public static Float lightLux;
TextView tvLightSensorLux;
public String Lux;
public void onCreate() {
Log.d("LightSensor", "OnCreate");
// Get an instance of the sensor service
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor LightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
// Test to see if Light Sensor is available
if (LightSensor != null) {
mSensorManager.registerListener(this, LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
public void onStartCommand() {
Log.d("LightSensor", "OnStartCommand");
}
/**
* protected void onResume() { mSensorManager.registerListener(this,
* LightSensor, SensorManager.SENSOR_DELAY_NORMAL); // super.onResume(); }
*
* protected void onPause() { mSensorManager.unregisterListener(this,
* LightSensor); // super.onPause(); }
**/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
lightLux = event.values[0]; // Final output of this sensor.
Lux = String.valueOf(lightLux);
if (lightLux > 0) {
Log.d("LightSensor", Lux);
sendLuxUpdate();
} else {
float lightLux = 0;
sendLuxUpdate();
}
}
private void sendLuxUpdate() {
Log.d("sender", "Broadcasting message " + Lux);
Intent intent = new Intent("LuxUpdate");
intent.putExtra("Lux", Lux);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
stopSelf();
mSensorManager.unregisterListener(this, LightSensor);
}
}
答案 0 :(得分:1)
问题是传感器会向您发送原始模拟数据。所以它们是连续的,数据是原始的。或者,如果您也使用其他传感器,则此方法可能会被其他传感器调用。所以也要检查传感器的类型。
public void onSensorChanged(SensorEvent event) {
lightLux = event.values[0]; // Final output of this sensor.
Lux = String.valueOf(lightLux);
if(event.sensor.getType()==Sensor.TYPE_LIGHT){
final float currentReading = event.values[0];
if (currentReading > 0){
//ON
}
else
{//OFF
}
}
}
此外,您每次都会看到值的变化,因为它会发送过于详细的值,因为它是原始数据。如果您不想要,可以将其强制转换为int
。
int value= (int) event.values[0];
希望它有所帮助!祝你好运