我想使用SensorManager但是为了检测设备在左或右方向上的摇动,我不知道如何检测设备的摇动方向是向右还是向左。我有以下问题:
如何使用SensorManager实现设备抖动?
如何检测设备的摇动方向?
答案 0 :(得分:20)
我尝试过这个,发现了一种方法。方法是,我正在监控X轴的值。如果阈值超过限制且X值超过我们给出的值,那么我们将得到一个Toast消息,我们向左或向右摇动手机。我试过这样的:
public class ShakeActivity extends Activity implements SensorListener {
// For shake motion detection.
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 800;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 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];
if(Round(x,4)>10.0000){
Log.d("sensor", "X Right axis: " + x);
Toast.makeText(this, "Right shake detected", Toast.LENGTH_SHORT).show();
}
else if(Round(x,4)<-10.0000){
Log.d("sensor", "X Left axis: " + x);
Toast.makeText(this, "Left shake detected", Toast.LENGTH_SHORT).show();
}
float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
// Log.d("sensor", "diff: " + diffTime + " - speed: " + speed);
if (speed > SHAKE_THRESHOLD) {
//Log.d("sensor", "shake detected w/ speed: " + speed);
//Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
}
答案 1 :(得分:2)
已被问及(并已解决)right here。