Can Xamarin control an accelerometer on Android?

I see that Xamarin has the documents for creating a gesture listener , but does not say anything that β€œshakes” the device only β€œrushes” to the screen. I am wondering if Xamarin for Android can listen to shake gestures? Does anyone know or has anyone tried? Thank you in advance.

+6
source share
1 answer

Here is a complete example that uses Android.Hardware.ISensorEventListener to detect a shake gesture. You should be able to opt out of this in your own projects without any problems.

 [Activity (Label = "ShakeDetection", MainLauncher = true)] public class MainActivity : Activity, Android.Hardware.ISensorEventListener { bool hasUpdated = false; DateTime lastUpdate; float last_x = 0.0f; float last_y = 0.0f; float last_z = 0.0f; const int ShakeDetectionTimeLapse = 250; const double ShakeThreshold = 800; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.Main); // Register this as a listener with the underlying service. var sensorManager = GetSystemService (SensorService) as Android.Hardware.SensorManager; var sensor = sensorManager.GetDefaultSensor (Android.Hardware.SensorType.Accelerometer); sensorManager.RegisterListener(this, sensor, Android.Hardware.SensorDelay.Game); } #region Android.Hardware.ISensorEventListener implementation public void OnAccuracyChanged (Android.Hardware.Sensor sensor, Android.Hardware.SensorStatus accuracy) { } public void OnSensorChanged (Android.Hardware.SensorEvent e) { if (e.Sensor.Type == Android.Hardware.SensorType.Accelerometer) { float x = e.Values[0]; float y = e.Values[1]; float z = e.Values[2]; DateTime curTime = System.DateTime.Now; if (hasUpdated == false) { hasUpdated = true; lastUpdate = curTime; last_x = x; last_y = y; last_z = z; } else { if ((curTime - lastUpdate).TotalMilliseconds > ShakeDetectionTimeLapse) { float diffTime = (float)(curTime - lastUpdate).TotalMilliseconds; lastUpdate = curTime; float total = x + y + z - last_x - last_y - last_z; float speed = Math.Abs(total) / diffTime * 10000; if (speed > ShakeThreshold) { Toast.MakeText(this, "shake detected w/ speed: " + speed, ToastLength.Short).Show(); } last_x = x; last_y = y; last_z = z; } } } } #endregion } 

The above activity implements the Android.Hardware.ISensorEventListener interface, and then registers it through the SensorManager . Actual sensor events (shaking, etc.) are passed to OnSensorChanged ; this is where we stick to the logic for our jitter detection code.

I based this answer on this , but made a few changes to it. First, this answer uses an ISensorEventListener , not an ISensorListener (which is deprecated at API level 3). And you will find that initial gesture detection is enabled (via hasUpdated ) and some variables to control the sensitivity of jitter. Playing with ShakeDetectionTimeLapse and ShakeDetectionThreshold , you can fine-tune it to your needs.

Cm:

+6
source

All Articles