我在我的MainActivity中实现了SensorEventListener,它运行得很好,我甚至可以说大部分时间。
但奇怪的是,有时它完全停止工作,我需要在每个方向上摇动它5-10秒,然后它神奇地重新开始。 好像是手机长时间处于闲置/睡眠状态之后。
我确实在onResume / onPause上实现了注册/取消注册。
这是我的代码,主要来自stackoverflow:
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 :(得分: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);