This recipe will show how to the accelerometer to measure a device’s motion in three dimensions.
Recipe
- Create a new Xamarin.Android application named MotionDector.
- Edit Main.axml so that it contains a single TextView:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/accelerometer_text" android:layout_width ="fill_parent" android:layout_height ="wrap_content" android:text=""/> </LinearLayout>
3. Add some instance variables to Activity1.cs:
private SensorManager _sensorManager;private TextView _sensorTextView;private static readonly object _syncLock = new object();
4. Have Activity1 implement the interface ISensorEventListener and implement the methods for the interface:
public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy) { // We don't want to do anything here. } public void OnSensorChanged(SensorEvent e) { lock (_syncLock) { var text = new StringBuilder("x = ") .Append(e.Values[0]) .Append(", y=") .Append(e.Values[1]) .Append(", z=") .Append(e.Values[2]); _sensorTextView.Text = text.ToString(); } }
5. Change OnCreate:
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); _sensorManager = (SensorManager) GetSystemService(Context.SensorService); _sensorTextView = FindViewById<TextView>(Resource.Id.accelerometer_text); }
6. Override OnResume so that the application will listen to updates from the accelerometer. The application will begin listening to updates from the accelerometer:
protected override void OnResume() { base.OnResume(); _sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.Accelerometer), SensorDelay.Ui); }
7. Override OnPause so that the application will stop listening to the accelerometer when the application is not active. This is done to reduce the drain on the battery and to preserve battery life:
protected override void OnPause() { base.OnPause(); _sensorManager.UnregisterListener(this); }
8. Run the application on a device. As the device is moved around, the accelerometer values will display on the screen.
Additional Information
The accelerometer returns values that describe the changes in acceleration along the three axes of the coordinate system measured in m/s2. These axes are show in the diagram below:

