mouvement_sexy164x300

Detecter les mouvements (Shotgun)08.02.11

Je voulais partager le bout de code sur lequel je me suis appuyé pour detecter le mouvement pour mes applications. Je ne l’ai pas inventé, mais j’ai du faire des petites corrections car certaines méthodes utilisées dans des exemples similaires étaient “deprecated”.
 
Voilà:

public class MyActivity extends Activity implements SensorEventListener{

	private SensorManager sensorMgr;
	private Sensor mAccelerometer;
    	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 350;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.myLayout);

		startMotionDetection();
	}

	private void startMotionDetection() {
		// start motion detection
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
		mAccelerometer = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		boolean accelSupported = sensorMgr.registerListener(this, mAccelerometer,
			SensorManager.SENSOR_ACCELEROMETER);

		if (!accelSupported) {
		    // on accelerometer on this device
		    sensorMgr.unregisterListener(this);
		}
	}

	protected void onPause() {
		if (sensorMgr != null) {
		    sensorMgr.unregisterListener(this);
		    sensorMgr = null;
	        }
		super.onPause();
	}

	protected void onResume(){
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
		sensorMgr.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_ACCELEROMETER);
		super.onResume();
	}

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

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
		    long curTime = System.currentTimeMillis();
		    // only allow one update every 100ms.
		    if ((curTime - lastUpdate) > 100) {
			long diffTime = (curTime - lastUpdate);
			lastUpdate = curTime;

			x = event.values[SensorManager.DATA_X];
			y = event.values[SensorManager.DATA_Y];
			z = event.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!
			    //Put your code here

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

 
En espérant que cela puisse vous aider!
 
Crédit photo: cyber-seb

Did you like this? Share it:

Tagged : ,

Posted by rmthbln under android.

Comments are closed.

© 2014 Actimust | Template by DemusDesign | WordPress theme by Theme Lab