コード例 #1
0
 public Task <WriteResult> WriteTag(NdefLibrary.Ndef.NdefMessage message, System.Threading.CancellationToken cancellationToken)
 {
     return(WriteTag(message, cancellationToken, TimeSpan.FromTicks(0)));
 }
コード例 #2
0
 public Task <WriteResult> WriteTag(NdefLibrary.Ndef.NdefMessage message, TimeSpan timeout)
 {
     return(WriteTag(message, CancellationToken.None, timeout));
 }
コード例 #3
0
        public void WriteTag(NdefLibrary.Ndef.NdefMessage message)
        {
            if (_droidTag == null)
            {
                throw new Exception("Tag Error: No Tag to write, register to NewTag event before calling WriteTag()");
            }

            Ndef ndef = GetNdef(_droidTag);

            if (ndef == null)
            {
                throw new Exception("Tag Error: NDEF not supported");
            }


            try
            {
                ndef.Connect();
                RaiseTagConnected(_nfcTag);
            }

            catch
            {
                throw new Exception("Tag Error: No Tag nearby");
            }

            if (!ndef.IsWritable)
            {
                ndef.Close();
                throw new Exception("Tag Error: Tag is write locked");
            }

            int size = message.ToByteArray().Length;

            if (ndef.MaxSize < size)
            {
                ndef.Close();
                throw new Exception("Tag Error: Tag is too small");
            }

            try
            {
                List <Android.Nfc.NdefRecord> records = new List <Android.Nfc.NdefRecord>();
                for (int i = 0; i < message.Count; i++)
                {
                    if (message[i].CheckIfValid())
                    {
                        records.Add(new Android.Nfc.NdefRecord(Android.Nfc.NdefRecord.TnfWellKnown, message[i].Type, message[i].Id, message[i].Payload));
                    }
                    else
                    {
                        throw new Exception("NDEFRecord number " + i + "is not valid");
                    }
                }
                ;
                Android.Nfc.NdefMessage msg = new Android.Nfc.NdefMessage(records.ToArray());
                ndef.WriteNdefMessage(msg);
            }

            catch (TagLostException tle)
            {
                throw new Exception("Tag Lost Error: " + tle.Message);
            }

            catch (IOException ioe)
            {
                throw new Exception("Tag IO Error: " + ioe.ToString());
            }

            catch (Android.Nfc.FormatException fe)
            {
                throw new Exception("Tag Format Error: " + fe.Message);
            }

            catch (Exception e)
            {
                throw new Exception("Tag Error: " + e.ToString());
            }

            finally
            {
                ndef.Close();
                RaiseTagTagDisconnected(_nfcTag);
            }
        }