2011-06-05 196 views
0

我從網站http://www.clingmarks.com/?p=25得到了這段代碼,我想要一些幫助!Android移動傳感器幫助

此代碼記錄手機的晃動。它只允許每100毫秒更新一次,抖動值必須超過800,SHAKE_THRESHOLD。

我有問題是,如果手機檢測到的抖動,(然後變量i ++)我想沒有能夠達到的代碼塊,在一定時間經過之前。

有人可以幫助我嗎?

public class ShakeActivity extends Activity implements SensorListener { 
    // For shake motion detection. 
    private SensorManager sensorMgr; 
    private long lastUpdate = -1; 
    private float x, y, z; 
    int i = 0; 
    private float last_x, last_y, last_z; 
    private static final int SHAKE_THRESHOLD = 800; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ...... // other initializations 
      // start motion detection 
      sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); 
     boolean accelSupported = sensorMgr.registerListener(this, 
       SensorManager.SENSOR_ACCELEROMETER, 
       SensorManager.SENSOR_DELAY_GAME); 

     if (!accelSupported) { 
      // on accelerometer on this device 
      sensorMgr.unregisterListener(this, 
        SensorManager.SENSOR_ACCELEROMETER); 
     } 
    } 

    protected void onPause() { 
     if (sensorMgr != null) { 
      sensorMgr.unregisterListener(this, 
        SensorManager.SENSOR_ACCELEROMETER); 
      sensorMgr = null; 
     } 
     super.onPause(); 
    } 

    public void onAccuracyChanged(int arg0, int arg1) { 
     // TODO Auto-generated method stub 
    } 

    public void onSensorChanged(int sensor, float[] values) { 
     if (sensor == SensorManager.SENSOR_ACCELEROMETER) { 
      long curTime = System.currentTimeMillis(); 
      // only allow one update every 100ms. 
      if ((curTime - lastUpdate) > 100) { 
       long diffTime = (curTime - lastUpdate); 
       lastUpdate = curTime; 

       x = values[SensorManager.DATA_X]; 
       y = values[SensorManager.DATA_Y]; 
       z = values[SensorManager.DATA_Z]; 

       float speed = Math.abs(x+y+z - last_x - last_y - last_z) 
        /diffTime * 10000; 
       if (speed > SHAKE_THRESHOLD) { 
        // yes, this is a shake action! Do something about it! 
        i++; 
       } 
       last_x = x; 
       last_y = y; 
       last_z = z; 
      } 
     } 
    } 
} 

回答

1

你想要的行爲被稱爲「釋放」。你想設置某個變量的活動對象:

private long last_shake_time = 0; 

,然後檢查和更新,在註冊表的抖動代碼:

  if (speed > SHAKE_THRESHOLD) { 
       // yes, this is a shake action! 
       long shake_time = System.currentTimeMillis(); 
       if (shake_time - last_shake_time >= SHAKE_HOLDOFF_MS) { 
        i++; 
        last_shake_time = shake_time; 
       } 
      } 

隨着SHAKE_HOLDOFF_MS定義就像SHAKE_THRESHOLD常數:

private static final long SHAKE_HOLDOFF_MS = 5000; 
1

設置您註冊搖一搖的時間的變量,System.currentTimeMillis()。然後當你再次搖一搖,比較當前時間和最後一次搖動時間。如果超過所需的延遲時間,請註冊新的搖動並更新最後的搖動時間。否則,不要做任何事情。