Android 1: Lesson 11

Android 1: Lesson 11: Accelerometer Part 2

In this lesson you will be getting access to your accelerometer. And being able to read the x, y, and z values that it gives it.
By the end of this lesson, you will be able to:
1. Access your accelerometer
2. Be able to read what the accelerometer is reading
3. Be able to set up a Sensor and SensorManager Activity

Required Reading
Read the following:
Introduction To Development Environment
·        Eclipse
·        Android
·        Considerations for beginning programming.
View the following:
1.      Eclipse
2.     Android Development
  1. Continuing onwards, hit Enter ‘layout = (RelativeLayout)findViewById(R.id.relative);’
  2. Enter ’title=(TextView)findViewById(R.id.name); ’
  3. Enter ’tv=(TextView)findViewById(R.id.xval);’
  4. Enter ’tv1=(TextView)findViewById(R.id.yval);’
  5. Enter ’tv2=(TextView)findViewById(R.id.zval);’
  6. The ‘onAccuracyChanged’ should be untouched, and you won’t need to add any code here.
  7. The ‘onSensorchanged’ however will need a bit of coding. After the brackets add ‘float x = event.values[0];’
  8. Do the same for y and z, but setting y values to 1, and z to 2.
  9. Enter ’title.setText(R.string.app_name); ’ you’ll actually want to type ‘app_name” here, because it is referring to the ‘string.xml’ document, which is under the ‘values’ folder.
  10. Enter ’tv.setText(“X axis” + “tt” + x); ‘
  11. You’ll want to do the same for the y and for the x.
  12. Just changing all xs to y and z, and ‘tv’ to ‘tv1’ for y and ‘tv2’ for z.
  13. Import ‘onResume’ and ‘onPause’ like you did for the ‘onCreate(Bundle)’
  14. Under ‘Resume’ , before the ending bracket, you’ll want to type ‘mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);’
  15. Now for ‘Pause’, again before the ending bracket, you’ll want to type ‘mSensorManager.unregisterListener(this);’
  16. Now open up your Manifest.You’ll need to do something slightly different this time. Copy and paste the MainActivity activity below it. And cut out the ‘action’ and the ‘category’ They are unneeded.
  17. Change ‘MainActivity’ to the ‘Accelerometer’
  18. Also open up the Menu.java and change one of the examples to the same as the Java for your accelerometer.
  19. Export the app and see what your phone reads! If laying on a table, x and y should both read about 0, not absolutely zero because it will read the tiniest vibration. z will read the pull on the phone, aka, gravity, so it should read around 9.8. All of the readings will be in meters per second.

Leave a Reply

Your email address will not be published. Required fields are marked *