我看到 Xamarin 有 Creating a Gesture Listener 的文档但与“摇动”设备无关,只是在屏幕上“ throw ”。我想知道 Xamarin for Android 是否能够监听摇动手势?有没有人知道或者有人试过?先感谢您。
最佳答案
这是一个使用 Android.Hardware.ISensorEventListener
的完整示例检测摇动手势。您应该能够毫不费力地将它放入您自己的项目中。
[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
}
以上 Activity 实现了Android.Hardware.ISensorEventListener
接口(interface),然后通过SensorManager
注册它.实际的传感器事件(摇动等)通过管道传输到 OnSensorChanged
;这是我们保存抖动检测代码逻辑的地方。
我的答案基于 this one但对其进行了一些修改。首先,这个答案使用 ISensorEventListener而不是 ISensorListener (在 API 级别 3 中已弃用)。您会发现包含开始手势检测(通过 hasUpdated
)和一些变量来控制摇动的灵敏度。通过使用 ShakeDetectionTimeLapse
和 ShakeDetectionThreshold
,您应该能够根据您的需要对其进行微调。
参见:
关于c# - Xamarin 可以处理 Android 上的振动加速度计吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23120186/