A very simple approach would be to give a chance for the sensor to give a new value in the upcoming n milliseconds (just as asked) would be the following:
1- Decide on how many milliseconds you want to give the user in order to undo his action (you used 800):
private static final long TIME_MARGIN_FOR_USER_TO_UNDO = 800;
2- Create a handler and a runnable to do your action (let them be in a bigger scope than your onSensorChanged - e.g. your activity):
Handler sensorHandler = new Handler();
Runnable toggleRunnable = new Runnable() {
public void run() {
toggleMethod();
}
}
3- Post this runnable whenever your if statement evaluates to true; However, post it after n milliseconds.
@Override
public void onSensorChanged(SensorEvent event) {
float z_value = event.values[2];
if (z_value < 0) {
sensorHandler.postDelayed(toggleRunnable, TIME_MARGIN_FOR_USER_TO_UNDO);
}
}
4- Since onSensorChanged will be called when the sensor values are changed, you can stop the runnable from running if the user fixed it. Therefore, you will need an else statement that will remove the runnable.
@Override
public void onSensorChanged(SensorEvent event) {
float z_value = event.values[2];
if (z_value < 0) {
sensorHandler.postDelayed(toggleRunnable, TIME_MARGIN_FOR_USER_TO_UNDO);
}
else {
sensorHandler.removeCallbacks(toggleRunnable);
}
}