如何以同步方式使用监听器?

时间:2012-10-10 14:48:27

标签: android listener synchronous

如果我没弄错的话......

如果启动侦听器,则代码将继续运行,并且当事件发生时,它会触发侦听器。所以它是异步的。

我想做的是以这种方式包装整个代码,从外部代码看它就像是同步调用。

之前(伪代码)

listener:
   oh, we just read temperature value

listener launch:
   register listener for temperature
   continue running
   ... 
   // somewhere here the temperature is read so we can obtain the value
   ...

以前代码的附加包装:

while (true)
  Thread.sleep(1000)
  if (is_temperature_read)
    break;

并致电:

temp = read_temperature()

令我惊讶的是,循环无限运行并且永远不会读取温度(即永远不会触发监听器)。如果没有用这样的循环包裹它,它就会被触发。

那么如何做正确的包装?

更新1/2:真实代码

现在,这是基于Sherif elKhatib(所有错误都是我的)。

主要代码:

    final Object lock = new Object();

听众的一部分:

        @Override
        public void onSensorChanged(SensorEvent event) 
        {
            synchronized (lock) 
            {
                read_value = event.values[0];
                sensor_manager.unregisterListener(this,proximity_sensor);
                lock.notifyAll();
            }
        }

等待听众:

          synchronized (lock)
          {
              try
              {
                  lock.wait();
              }
              catch (InterruptedException ex)
              {
              }
          }

更新2/2:从另一个线程调用

这不是解决方案,只是一个评论。如果我从ad-hoc创建的新Thread调用这个同步包装器,它就不会陷入死锁。

所以可能其他东西锁定代码。

1 个答案:

答案 0 :(得分:2)

你应该锁定线程(如果这是你想要的)

这是代码(我没有测试,所以它可能需要这里或那里的东西)

public wrapperFunction() {
    Object object = new Object();
    call(bla_parameters, new listener() {
        public void onEnd() {
             synchronized(object) {
                 object.notifyAll();
             }
        }
    });
    try {
         synchronized(object) {
             object.wait();
         }
    } catch(Exception ex){}

}