要通过 NFC 标签启动您的应用程序,您需要通过在文件中添加扩展名来注册 URI 关联WMAppManifest.xml
,如下所示:
<Extensions>
<Protocol Name="mynfcapp" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" />
</Extensions>
然后您将需要创建一个可以处理 URI 关联的 URI 映射器,如下所示:
public class AssociationUriMapper : UriMapperBase
{
public override Uri MapUri(Uri uri)
{
string url = HttpUtility.UrlDecode(uri.ToString());
if (url.Contains("mynfcapp:MainPage"))
{
int paramIndex = url.IndexOf("source=") + 7;
string paramValue = url.Substring(paramIndex);
return new Uri("/MainPage.xaml?source=" + paramValue, UriKind.Relative);
}
return uri;
}
}
下面是编写将启动应用程序的 NFC 标签的代码:
public partial class MainPage : PhoneApplicationPage
{
private readonly ProximityDevice _proximityDevice;
private long subId = 0;
private long pubId = 0;
public MainPage()
{
InitializeComponent();
_proximityDevice = ProximityDevice.GetDefault();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (_proximityDevice != null)
subId = _proximityDevice.SubscribeForMessage("WriteableTag", OnWriteableTagArrived);
base.OnNavigatedTo(e);
}
private void OnWriteableTagArrived(ProximityDevice sender, ProximityMessage message)
{
var dataWriter = new DataWriter();
dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
string appLauncher = string.Format(@"mynfcapp:MainPage?source=mynfctest");
dataWriter.WriteString(appLauncher);
pubId = sender.PublishBinaryMessage("WindowsUri:WriteTag", dataWriter.DetachBuffer());
}
}