Using the Android accelerometer

I am building my first real Android application. It is a Hindi flashcards application. It works already (in that it will shows the different Devanagari characters and English transliterations) but now needs some better UI features.

The first one I am going to implement is shuffling the deck of cards by shaking the phone, using its accelerometer. To handle accelerometer events, you need to get a reference to the SensorManager and then register a new SensorEventListener using the registerListener method:

SensorManager sensor = (SensorManager)getBaseContext().getSystemService(SENSOR_SERVICE); sensor.registerListener(new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }, sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);

I figured out the rest of it from a forum on

I haven’t tried it, but I’m guessing it will work. Looks like it combined the x, y and z acceleration, and checks that the current and previous values of the combined acceleration are before and after a predetermined threshold. I think there’s some intelligent physics involved in that but it’s been 10 years since I learnt any physics!

One thing wrong with the post on is that it’s using an old version of the Android API.

The next post will be about using a slide motion on the touch screen to move between cards (without animation, though).

Built with Hugo
Theme Stack designed by Jimmy