Android 从OnSensorChanged()方法返回值
我想要实现的是在方法Android 从OnSensorChanged()方法返回值,android,return,proximity,Android,Return,Proximity,我想要实现的是在方法isClose中返回正确的结果集。问题在于isClose方法没有等待触发onSensorChanged,并返回isClose字段的默认“0”值 我这样称呼我的Position类: Position mPosition=新位置() boolean result=mPosition.isInPocket(此) 职位类别: public class Position implements SensorEventListener { private SensorManager
isClose
中返回正确的结果集。问题在于isClose
方法没有等待触发onSensorChanged
,并返回isClose
字段的默认“0”值
我这样称呼我的Position类:Position mPosition=新位置()代码>
boolean result=mPosition.isInPocket(此)代码>
职位类别:
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.
}
}
您需要让主线程在isClose
中等待对于第一个onSensorChanged
事件,您可以通过多种方式实现这一点,但使用变量可能是最简单的方法
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.
}
我省略了上面代码中的InterrupedException
检查,但它应该会给您一个想法