简单的方向传感器SimpleOrientationSensor

SimpleOrientationSensor是一个简单的方向传感器。能够识别手机如下表的6种方向信息:

SimpleOrientation枚举变量 方向
NotRotated 设备未旋转
Rotated90DegreesCounterclockwise 逆时针旋转 90 度
Rotated180DegreesCounterclockwise 逆时针旋转 180 度
Rotated270DegreesCounterclockwise 逆时针旋转 270 度
Faceup 将设备面朝上
Facedown 将设备面朝下

下面我们就来实现是否开打方向处理器并在各个不同状态下进行处理。

(一般的,我都是会将很多代码写在主函数里面,导致代码太臃肿,维护性差,现在我们将它封装起来吧。)

MainPage.xaml.cs:

        <ToggleSwitch x:Name="toggleSwitch" Header="方向传感器" IsOn="{Binding IsOpen, Mode=TwoWay}"/>

OrtSensors.cs类:

   /// <summary>
/// 自定义一个方向传感器类
/// </summary>
public class OrtSensors
{
public static SimpleOrientationSensor SimpleOrtSensor = SimpleOrientationSensor.GetDefault();//简单方向传感器 private bool isOpen; //是否打开 public bool IsOpen
{
set
{
if (value)
{
SimpleOrtSensor.OrientationChanged += SimpleOrtSensor_OrientationChanged;
}
else if (!value)
{
SimpleOrtSensor.OrientationChanged -= SimpleOrtSensor_OrientationChanged;
}
isOpen = value;
}
get
{
return isOpen;
}
} void SimpleOrtSensor_OrientationChanged(SimpleOrientationSensor sender,
SimpleOrientationSensorOrientationChangedEventArgs args)
{
switch (args.Orientation)
{
case SimpleOrientation.NotRotated:
Debug.WriteLine(args.Orientation.ToString()); //设备未旋转
break;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
Debug.WriteLine(args.Orientation.ToString()); //逆时针180
break;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
Debug.WriteLine(args.Orientation.ToString()); //逆时针270
break;
case SimpleOrientation.Rotated90DegreesCounterclockwise:
Debug.WriteLine(args.Orientation.ToString()); //逆时针90
break;
case SimpleOrientation.Facedown:
Debug.WriteLine(args.Orientation.ToString()); //面朝下
break;
case SimpleOrientation.Faceup:
Debug.WriteLine(args.Orientation.ToString()); //面朝上
break;
default:
break;
}
}
}

MainPage.cs:

//实例化并且设置绑定源
OrtSensors sensor = new OrtSensors();
public MainPage()
{
this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required;
toggleSwitch.DataContext = sensor;
}
上一篇:SpringCloud(2) 服务注册和发现Eureka Server


下一篇:青蛙怕楼梯问题