Hello developers,
I have got a problem concerning the SensorListener. At the moment I
can already detect if the phone got shaken. Addtionally I now want to
detect in which direction the phone is shaken. Do you maybe know which
values I have to consider to detect this?
My code at the moment looks like this:
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 float raw_x, last_raw_x;
private static final int SHAKE_THRESHOLD = 800;
private final float shakeThreshold = 1.5f;
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) {
Log.d("sensor", "onSensorChanged: " + sensor);
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];
raw_x = SensorManager.GRAVITY_EARTH;
float xChange = Math.abs(x - last_x);
float speed = Math.abs(x + y + z - last_x - last_y -
last_z)
/ diffTime * 10000;
float deltaX = Math.abs(last_x - x);
float deltaY = Math.abs(last_y - y);
float deltaZ = Math.abs(last_z - y);
float delta_raw_x = raw_x - last_raw_x;
// 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 + "; accelX:
"
+ xChange, Toast.LENGTH_SHORT).show();
// now left,right,up,down movement has to be detected
// somehow
}
last_x = x;
last_y = y;
last_z = z;
last_raw_x = raw_x;
}
}
}
}
Best regards,
tsemann
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en