How to launch app using NFC tag on Windows Phone 8?

后端 未结 2 1747
星月不相逢
星月不相逢 2021-02-06 17:16

I got Windows Phone 8 device, few NDEF formatted NFC tags and I\'m wondering, is it possible to implement app launching on my WP8 using these tags? I\'ve read thoroughly this ar

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 17:34

    To launch your app via a NFC tag, you need to Register it for a URI association by adding an extension in the WMAppManifest.xml file, like this:

    
      
    
    

    Then you will need to create a URI mapper that can handle the URI association, like this:

    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;
        }
    }
    

    And here is the code to write the NFC tag that will launch the app:

    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());
        }
    }
    

提交回复
热议问题