Posts contrassegnato dai tag ‘shake’

Shake – Android Developer

Pubblicato: 23 maggio 2011 in Android, Programmazione
Tag:,

Here an example to use the shake on android device

// Need to implement SensorListener
public class ShakeActivity extends Activity implements SensorEventListener {
    //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);
        ...... // other initializations
	// start motion detection
	sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
    }

    public void onAccuracyChanged(int arg0, int arg1) {
	// TODO Auto-generated method stub
    }

    public void onSensorChanged(SensorEvent event){
	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 = event.values[0];
		y = event.values[1]
		z = event.values[2];

		float speed = Math.abs(x+y+z - last_x - last_y - last_z)
                              / diffTime * 10000;

		if (speed > SHAKE_THRESHOLD) {// THIS IS A SHAKE ACTION - WRITE YOUR CODE HERE}

		last_x = x;
		last_y = y;
		last_z = z;
	    }
	}
    }
}
Annunci