0

我想要实现的是在 method 中返回正确的结果集isClose。问题是该isClose方法没有等待onSensorChanged被触发并返回字段的默认“0”值isClose

我这样称呼我的职位类:
Position mPosition = new Position();

boolean result = mPosition.isInPocket(this);

职位类别:

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. 
}


}
4

1 回答 1

0

您需要waitisClose第一个onSensorChanged事件中加入主线程,您可以通过多种方式实现这一点,但使用Condition变量可能是最简单的。

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从上面的代码中省略了检查,但它应该给你一个想法。

于 2013-01-19T15:32:51.903 回答