2016-03-11 58 views
0

我已經在我的MainActivity實施SensorEventListener,它工作得很好,我連說大部分時間非常好。SensorEventListener暫時不工作

但古怪,有時完全停止工作,我要動搖它在每一個方向5-10秒,它的神奇回來。 這似乎是後電話空閒/睡着了很長一段時間。

我沒上實現的onResume /的onPause登記/註銷。

這是我的代碼,其中大部分來自計算器來:

SensorManager sensorManager; 

private float accel; // acceleration apart from gravity 
private float accelCurrent; // current acceleration including gravity 
private float accelLast; // last acceleration including gravity 
private static final float SHAKE_THRESHOLD = 12.f; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    initSensor(); 
} 


private void initSensor() { 
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
    registerSensor(); 
} 

private void registerSensor() { 
    HandlerThread handlerThread = new HandlerThread(HANDLER_THREAD_NAME_SENSOR); 
    handlerThread.start(); 
    Handler handler = new Handler(handlerThread.getLooper()); 
    sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL, handler); 
    accel = 0.00f; 
    accelCurrent = SensorManager.GRAVITY_EARTH; 
    accelLast = SensorManager.GRAVITY_EARTH; 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    sensorManager.unregisterListener(this); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    registerSensor(); 
} 

@Override 
public void onSensorChanged(SensorEvent event) { 
    float x = event.values[0]; 
    float y = event.values[1]; 
    float z = event.values[2]; 
    accelLast = accelCurrent; 
    accelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z)); 
    float delta = accelCurrent - accelLast; 
    accel = accel * 0.9f + delta; // perform low-cut filter 
    //Log.d(TAG, ">>> ALL shake accel = "+ accel); 
    if (accel > SHAKE_THRESHOLD) { 
     Log.d(TAG, "shake accel = "+ accel); 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       // Do stuffs in the UI 
      } 
     }); 

    } 
} 

@Override 
public void onAccuracyChanged(Sensor sensor, int accuracy) { 
    // Nothing do to here 
} 
+0

你註銷你的聽衆在'onPause'當您的手機進入睡眠狀態,這將很可能被調用,你只能在'onCreate'註冊。如果手機進入睡眠狀態時您的活動可見,則在您喚醒手機時不會創建該活動。相反,它是我的簡歷(谷'onResume'),我想你應該在回調 – 0xDEADC0DE

+0

再次註冊偵聽嘿感謝您的回答。雖然你可以在我的代碼中看到我確實實施了onResume,但我重新註冊了傳感器。 –

+0

我可能沒注意,當我輸入我的評論,因爲我完全錯過了。抱歉! – 0xDEADC0DE

回答

0

它被固定,通過改變傳感器延遲SensorManager.SENSOR_DELAY_FASTEST; 註冊現在看起來像:

// Global 
private static final String HANDLER_THREAD_NAME_SENSOR = "sensorThread"; 

// ...Registration 
HandlerThread handlerThread = new HandlerThread(HANDLER_THREAD_NAME_SENSOR); 
handlerThread.start(); 
Handler handler = new Handler(handlerThread.getLooper()); 
mSensorManager.registerListener(this, 
        mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
        SensorManager.SENSOR_DELAY_FASTEST, 
        handler);