大きな揺れを測定したい(例:自転車や車が事故に遭ったときの測定。その電話の揺れを測定したい)。携帯を振ったときにオーディオを再生するコードがあります。しかし、SHAKE_THRESHOLD 値を高いレベルに変更すると、機能しませんでした。大きな揺れも計測できますか?
マイコード:
public class ShakeActivity extends Activity implements SensorListener{
// For shake motion detection.
private MediaPlayer mPlayer1;
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 = 8000;
/** Called when the activity is first created. */
@Override
public 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();
}
@Override
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub
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!
MediaPlayer mPlayer1 = MediaPlayer.create(this, R.raw.hello);
try {
mPlayer1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer1.start();
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
}