What I’d like to achieve is to return the correct result set in method isClose. The problem is theisClose method is not waiting for onSensorChanged to be triggered and returns the default “0” value of isClose field.
I call my Position class like this:
Position mPosition = new Position();
boolean result = mPosition.isInPocket(this);
Position class:
public class Position implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
private boolean isClose;
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
float[] value = event.values;
if(value[0] > 0) {
isClose = false;
} else
{
isClose = true;
}
}
public boolean isClose(Context context) {
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(this, mProximity, 0);
return isClose; // I'd like to return this with value set in onSensorChanged.
}
}
You’ll need to have your main thread
waitinisClosefor the firstonSensorChangedevent, you can achieve this in many ways, but using aConditionvariable would probably be the easiest.I’ve omitted
InterrupedExceptionchecks from the above code, but it should give you an idea.