2013-01-19 167 views
0

我想實現的是在方法isClose中返回正確的結果集。問題是isClose方法不會等待onSensorChanged被觸發,並返回isClose字段的默認「0」值。從OnSensorChanged()方法返回值

我打電話給我的位置類這樣的:
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. 
} 


} 

回答

0

你需要讓你的主線程waitisClose第一個onSensorChanged事件,你可以通過很多方式實現這一點,但使用Condition變量將p可以說是最簡單的。

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從上面的代碼中檢查,但它應該給你一個想法。