我试图实现一种可以检测手波的传感器。我发现了一个可以手动悬停的例子,但不是手波。
我使用的以下代码来自 How to controlandroid proximity sensor?
public class AndroidProximitySensorActivity extends Activity {
TextView ProximitySensor, ProximityMax, ProximityReading;
SensorManager mySensorManager;
Sensor myProximitySensor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProximitySensor = (TextView)findViewById(R.id.proximitySensor);
ProximityMax = (TextView)findViewById(R.id.proximityMax);
ProximityReading = (TextView)findViewById(R.id.proximityReading);
mySensorManager = (SensorManager)getSystemService(
Context.SENSOR_SERVICE);
myProximitySensor = mySensorManager.getDefaultSensor(
Sensor.TYPE_PROXIMITY);
if (myProximitySensor == null){
ProximitySensor.setText("No Proximity Sensor!");
}else{
ProximitySensor.setText(myProximitySensor.getName());
ProximityMax.setText("Maximum Range: "
+ String.valueOf(myProximitySensor.getMaximumRange()));
mySensorManager.registerListener(proximitySensorEventListener,
myProximitySensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
SensorEventListener proximitySensorEventListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
ProximityReading.setText("Proximity Sensor Reading:"
+ String.valueOf(event.values[0]));
}
}
};
}
在上面的代码中,当event.values [0] = 0时,表示我的手悬停在传感器上。但是,我需要我的传感器来检测手波。我该怎么做?感谢。
答案 0 :(得分:0)
请尝试以下代码:
private SensorManager sensorManager;
private Sensor proximitySensor;
private final int WAVE_TIME = 2000;
private final int WAVE_NEEDED_MOVEMENTS = 3;
private long lastWaveTime = 0;
private float lastSensorValue;
private float maxSensorValue;
private float numOfMovements = 0;
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sensorManager.registerListener(proximitySensorEventListener, proximitySensor,SensorManager.SENSOR_DELAY_NORMAL);
maxSensorValue = proximitySensor.getMaximumRange();
}
@Override
public void onSensorChanged(SensorEvent event) {
if(lastWaveTime + WAVE_TIME > System.currentTimeMillis()) {
System.out.println("Reset timing...");
lastWaveTime = System.currentTimeMillis();
numOfMovements = 0;
lastSensorValue = event.values[0];
} else if((event.values[0] != maxSensorValue && lastSensorValue == maxSensorValue) || (event.values[0] == maxSensorValue && lastSensorValue != maxSensorValue) ){
numOfMovements++;
if(numOfMovements == WAVE_NEEDED_MOVEMENTS) {
System.out.println("WAVE EVENT");
lastWaveTime = System.currentTimeMillis();
numOfMovements = 0;
}
}
}