这篇介绍如何在 Windows 8/Windows Phone 8 上使用 Proximity API 侦测
当我们要撰写关于 NFC 设备相关程序的第一件事就是在资讯清单中声明使用近场通讯的能力。
Windows 8 | Windows Phone 8 |
声明 Proximity | 声明 ID_CAP_PROXIMITY |
这篇的范例程序非常基础,用途只有侦测是否有另一个近接设备 (包含 Tag) 的载波被侦测到。
[范例一 Windows Phone 8 ]
public partial class MainPage : PhoneApplicationPage
{
private ProximityDevice proximitydevice;
public MainPage()
{
InitializeComponent();
proximitydevice = ProximityDevice.GetDefault();
if (proximitydevice != null)
{
proximitydevice.DeviceArrived += proximitydevice_DeviceArrived;
proximitydevice.DeviceDeparted += proximitydevice_DeviceDeparted;
}
else
{ MessageBox.Show("此设备不具备 NFC 功能"); }
}
private void proximitydevice_DeviceDeparted(ProximityDevice sender)
{ Dispatcher.BeginInvoke(() => WriteMessage("离开"));}
private void proximitydevice_DeviceArrived(ProximityDevice sender)
{ Dispatcher.BeginInvoke(() => WriteMessage("进入")); }
private void WriteMessage(string message)
{ msgtxt.Text = message; }
}
这个范例非常简单只用到 ProximityDevice 类 ,一开始我们必须先使用 ProximityDevice.GetDefault() 静态方法来取得系统中的 NFC 设备,要注意的一点是它只管‘有没有’NFC 设备,只要是有 NFC 设备回传值就不会是 null;换言之,这个方法并没有办法确认 NFC 设备是处在开启或关闭的状态。
接着为两个事件 ProximityDevice.DeviceArrived (代表有其它设备进入到载波范围) 与 ProximityDevice.DeviceDeparted (代表有个原来在载波范围内的设备已经脱离) 加入其事件委派函数:proximitydevice_DeviceArrived 与 proximitydevice_DeviceDeparted,特别要注意的一件事情是这两个事件的委派函数会在另一个线程中执行,所以必须透过 Dispatcher.BeginInvoke 方法 来变更 UI 控件。
[范例二 Windows 8 ]
public sealed partial class MainPage : Page
{
private ProximityDevice proximitydevice;
public MainPage()
{
this.InitializeComponent();
proximitydevice = ProximityDevice.GetDefault();
if (proximitydevice != null)
{
proximitydevice.DeviceArrived += proximitydevice_DeviceArrived;
proximitydevice.DeviceDeparted += proximitydevice_DeviceDeparted;
}
else
{ msgtxt.Text = "此设备不具备 NFC 功能"; }
}
async private void proximitydevice_DeviceDeparted(ProximityDevice sender)
{ await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => WriteMessage("离开")); }
async private void proximitydevice_DeviceArrived(ProximityDevice sender)
{ await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => WriteMessage("进入")); }
private void WriteMessage(String message)
{ msgtxt.Text = message; }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
Windows Store App 的写法和 Windows Phone 8 几乎是一样,唯一的不同是跨线程的处理是使用 CoreDispatcher.RunAsync 方法 ,我看过很多关于 Windows Phone Proximity 博客的文章,他们的 Sample Code 都长的和 Windows Store App 一样用 CoreDispatcher.RunAsync 方法 (是的,包含微软在 Windows phone 8 Dev Center 自己的 Sample ) ,但我从来未曾把那个程序编译成功过;我也曾在 Windows phone 8 项目上试过很多种不同的方式来调用 CoreDispatcher.RunAsync 方法 ,不过截至目前一直处在失败的结局。如果有人试成功怎么在 Windows Phone 上用 CoreDispatcher.RunAsync 方法,麻烦告诉我一下是怎么弄出来的。
原文:大专栏 [NFC] NFC 设备载波侦测 (Windows 8/ Windows Phone 8)