Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Accelerometer in Android Applications
[Activity(Label = "Accelerometer_Droid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, ISensorEventListener
{
private SensorManager _sensorManager;
private static readonly object _syncLock = new object();
private TextView x_axis; private TextView y_axis; private TextView z_axis;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
_sensorManager = (SensorManager)GetSystemService(Context.SensorService);
x_axis = FindViewById<TextView>(Resource.Id.lblXAxis);
y_axis = FindViewById<TextView>(Resource.Id.lblYAxis);
z_axis = FindViewById<TextView>(Resource.Id.lblZAxis);
}
public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
{
//Doing nothing. Just implementing interface.
}
public void OnSensorChanged(SensorEvent e)
{
lock (_syncLock)
{
x_axis.Text = e.Values[0].ToString("F");
y_axis.Text = e.Values[1].ToString("F");
z_axis.Text = e.Values[2].ToString("F");
}
}
protected override void OnResume()
{
base.OnResume();
_sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.Accelerometer), SensorDelay.Ui);
}
protected override void OnPause()
{
base.OnPause();
_sensorManager.UnregisterListener(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.