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 wait
in isClose
for the first onSensorChanged
event, you can achieve this in many ways, but using a Condition
variable would probably be the easiest.
public class Position implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
private boolean isClose;
private final Lock lock = new ReentrantLock();
private final Condition eventReceived = lock.newCondition();
private boolean firstEventOccurred = false;
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;
}
if (!firstEventOccurred) {
lock.lock();
try {
firstEventOccurred = true;
eventReceived.signal();
} finally {
lock.unlock();
}
}
}
public boolean isClose(Context context) {
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(this, mProximity, 0);
lock.lock();
try {
while (!firstEventOccurred) {
eventReceived.await();
}
} finally {
lock.unlock();
}
return isClose; // I'd like to return this with value set in onSensorChanged.
}
I've omitted InterrupedException
checks from the above code, but it should give you an idea.