我需要有关如何检测安卓设备移动量的建议。假设我将手机放在 table 或床上,然后如果有人敲击 table 或坐在床上或躺在床上,那么我想检测 android 设备的移动。
实际上我知道 android 有运动传感器 API,但我不知道使用哪种传感器以及哪种传感器类型最适合这种类型的运动检测。
如果有人可以分享一些基本的演示代码,我会很高兴。
最佳答案
一定要使用加速度计:
// Start with some variables
private SensorManager sensorMan;
private Sensor accelerometer;
private float[] mGravity;
private float mAccel;
private float mAccelCurrent;
private float mAccelLast;
// In onCreate method
sensorMan = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
// And these:
@Override
public void onResume() {
super.onResume();
sensorMan.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
super.onPause();
sensorMan.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
mGravity = event.values.clone();
// Shake detection
float x = mGravity[0];
float y = mGravity[1];
float z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = FloatMath.sqrt(x*x + y*y + z*z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
// Make this higher or lower according to how much
// motion you want to detect
if(mAccel > 3){
// do something
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// required method
}
关于android - 如何检测安卓设备的移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574879/