Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试写入标记时,Xamarin NFC视图刷新_Xamarin_Nfc - Fatal编程技术网

尝试写入标记时,Xamarin NFC视图刷新

尝试写入标记时,Xamarin NFC视图刷新,xamarin,nfc,Xamarin,Nfc,我希望我能正确地解释这一点。如果我做不到,请原谅我 我有一个适用于Android的Xamarin NFC应用程序。您登录应用程序,触摸NFC卡,它读取卡上的信息,然后触摸按钮移动到新的目的地,然后在该视图中,您可以键入内容,轻触卡,它应该会写入卡 在最后一个视图中实际发生的情况是,当您点击该卡时,它将刷新完全相同的视图,然后再次点击,然后它才会写入NFC卡 所以我认为我需要做的是停止NFC感知必须写入NFC卡的视图-它应该只处于写入模式,而不是读取模式 如果您有任何想法,我们将不胜感激,谢谢 第

我希望我能正确地解释这一点。如果我做不到,请原谅我

我有一个适用于Android的Xamarin NFC应用程序。您登录应用程序,触摸NFC卡,它读取卡上的信息,然后触摸按钮移动到新的目的地,然后在该视图中,您可以键入内容,轻触卡,它应该会写入卡

在最后一个视图中实际发生的情况是,当您点击该卡时,它将刷新完全相同的视图,然后再次点击,然后它才会写入NFC卡

所以我认为我需要做的是停止NFC感知必须写入NFC卡的视图-它应该只处于写入模式,而不是读取模式

如果您有任何想法,我们将不胜感激,谢谢

第一次点击卡时不会调用OnNewIntent

编辑-在代码中添加

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Nfc;
using Android.Nfc.Tech;
using Android.Preferences;
using Java.IO;
using System.Threading.Tasks;
using System.Net.Http;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace [removed]
{
[Activity(Label = "Update Card")]
public class NfcWriter : Activity
{
    public static readonly string PREFERENCE_FILENAME = "[removed]";
    public static readonly string CLIENTID = "CLIENTID";
    public static readonly string CLIENTUSERID = "CLIENTUSERID";

    public static readonly string EMAILADDRESS = "EMAILADDRESS";
    public static readonly string CARDID = "CARDID";
    public static readonly string USERID = "USERID";
    public static readonly string BALANCE = "BALANCE";

    public const string ViewApeMimeType     = "application/[removed]";//"application/[removed]";
    private bool _inWriteMode;
    private NfcAdapter _nfcAdapter;
    private TextView _textView;
    private Button _writeTagButton;
    private AutoCompleteTextView _textEmail;
    public static readonly string Tag = "NFC Writer";
    public static string uuid = "";

    private TextView _textCard;
    private EditText _textAmount;
    private static string cardID;
    private static double balance;
    private static double newBalance;

    private TextView _txtCard;
    private TextView _txtBalance;
    private TextView _txtProduct;
    private TextView _txtTotalPrice;

    private static string layout;

    private double amount = 0.0f;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        var c = (Context)this;

        // get the nfc device adapter
        _nfcAdapter = NfcAdapter.GetDefaultAdapter(this);

        var allxsSettings = c.GetSharedPreferences(PREFERENCE_FILENAME, FileCreationMode.Private);
        layout = allxsSettings.GetString("Layout", "Registration");


        if (layout == "Registration")
        {
            SetContentView(Resource.Layout.writer);
            if (Intent == null)
            {
                return;
            }

            _writeTagButton = FindViewById<Button>(Resource.Id.write_tag_button);
            _writeTagButton.Click += WriteTagButtonOnClick;

            _textView = FindViewById<TextView>(Resource.Id.text_view);

            _textEmail = FindViewById<AutoCompleteTextView>(Resource.Id.EmailID);
            _textEmail.Text = "";
        }

        if (layout == "CashLoad")
        {
            //_inWriteMode = true;
            SetContentView(Resource.Layout.LoadCash);
            if (Intent == null)
            {
                return;
            }

            _writeTagButton = FindViewById<Button>(Resource.Id.btnLoadCash);
            _writeTagButton.Click += WriteTagButtonOnClick;

            _textView = FindViewById<TextView>(Resource.Id.text_view);

            _textAmount = FindViewById<EditText>(Resource.Id.txtCash);
            _textCard = FindViewById<TextView>(Resource.Id.txtCardId);

            cardID = allxsSettings.GetString (CARDID, "");
            var tempBalance = allxsSettings.GetFloat(BALANCE, 0.0f);
            balance = Convert.ToDouble(tempBalance);

            _textCard.Text = cardID;
            _textAmount.Text = "";
        }

        if (layout == "Sale") {
            //_inWriteMode = true;
            SetContentView(Resource.Layout.Sale);
            if (Intent == null)
            {
                return;
            }

            _writeTagButton = FindViewById<Button>(Resource.Id.btnSale);
            _writeTagButton.Click += WriteTagButtonOnClick;

            _textView = FindViewById<TextView>(Resource.Id.text_view);

            _txtBalance= FindViewById<TextView>(Resource.Id.txtCash);
            _txtCard = FindViewById<TextView>(Resource.Id.txtCardId);
            _txtProduct=FindViewById<TextView>(Resource.Id.txtProduct);
            _txtTotalPrice=FindViewById<TextView>(Resource.Id.txtPrice);

            cardID = allxsSettings.GetString (CARDID, "");
            var tempBalance = allxsSettings.GetFloat (BALANCE, 0.0f);
            balance = Convert.ToDouble(tempBalance);

            _txtCard.Text = cardID;
            _txtBalance.Text = balance.ToString("0.00");

            Product productRow = null;

            decimal totalAmount = 0;
            _txtProduct.Text = "";

            foreach (var salesRow in SalesManager.GetSaless()) {
                productRow = ProductManager.GetProduct (salesRow.ProductID);

                totalAmount += Convert.ToDecimal (salesRow.TotalAmount);

                if (_txtProduct.Text.Length != 0)
                    _txtProduct.Text += "\n";

                _txtProduct.Text += salesRow.NoOfUnits + " x " + productRow.ProductName + " @ " + productRow.UnitPrice.ToString ("0.00");
            }

            _txtTotalPrice.Text = totalAmount.ToString("0.00");

            // determine the new card balance
            newBalance = balance - Convert.ToDouble (totalAmount);

            if (newBalance < 0) {
                // we don't have enough money to buy
                _txtTotalPrice.Text += " INSUFFICIENT FUNDS";

                toast ("INSUFFICIENT FUNDS - NO SALE");
            }
        }

    }

    /// <summary>
    /// This method is called when an NFC tag is discovered by the application.
    /// </summary>
    /// <param name="intent"></param>
    protected override void OnNewIntent(Intent intent)
    {
        _inWriteMode = true;

        if (_inWriteMode)
        {
            //_inWriteMode = false;

            var c = (Context)this;
            var allxsSettings = c.GetSharedPreferences(PREFERENCE_FILENAME, FileCreationMode.Private);

            var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
            if (tag == null)
            {
                return;
            }


            Card card = new Card ();
            if (layout == "Registration") {

                card.CardID = _textEmail.Text;
                card.Amount = 0.0f;
            } 
            if (layout == "CashLoad") {
                card.CardID = _textCard.Text;
                card.Amount = balance;
            }

            if (layout == "Sale") {

                // no write allowed if there is no money
                if (newBalance < 0) {
                    toast ("INSUFFICIENT FUNDS - NO SALE");
                    return;
                }

                var cardID = allxsSettings.GetString (CARDID, "");
                var tempBalance = allxsSettings.GetFloat (BALANCE, 0.0f);
                var balance = Convert.ToDouble(tempBalance);
                var clientUserId = allxsSettings.GetInt (CLIENTUSERID, 0);

                card.CardID = cardID;
                card.Amount = newBalance;
            }


            BinaryFormatter payload = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            payload.Serialize(ms, card);

            var mimeBytes = Encoding.ASCII.GetBytes(ViewApeMimeType);
            var cardRecord = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], ms.ToArray());
            var ndefMessage = new NdefMessage(new[] { cardRecord });

            bool isWritten = false;

            if (!TryAndWriteToTag(tag, ndefMessage))
            {
                // Maybe the write couldn't happen because the tag wasn't formatted?
                if (TryAndFormatTagWithMessage(tag, ndefMessage))
                    isWritten = true;

            }
            else
            {
                isWritten = true;
            }

            // if we did write to the card then we must update the server api (this is where the transaction should be stored locally and updated later)
            if (isWritten)
            {
                if (layout == "Registration")
                {
                    // this is a new card - we don't know who the user is at this time but send the card registration to the system
                    ApiCardRegistration(card.CardID);
                }

                if (layout == "CashLoad")
                {
                    // tell the api that we have loaded cash
                    ApiCardLoadCash(card.CardID, amount);
                }

                if (layout == "Sale")
                {
                    // we have written the sale amount to the card, now write to the server
                    ApiCardLoadProducts (card.CardID);

                }
            }


            ISharedPreferencesEditor prefEditor = allxsSettings.Edit();
            prefEditor.PutString("Layout", "");     
            prefEditor.Apply();
            prefEditor.Commit();

        }
    }




    protected override void OnPause()
    {
        base.OnPause();
        // App is paused, so no need to keep an eye out for NFC tags.
        if (_nfcAdapter != null)
            _nfcAdapter.DisableForegroundDispatch(this);
    }

    private void DisplayMessage(string message)
    {
        _textView.Text = message;
        //Log.Info(Tag, message);
    }

    /// <summary>
    /// Identify to Android that this activity wants to be notified when 
    /// an NFC tag is discovered. 
    /// </summary>
    private void EnableWriteMode()
    {
        _inWriteMode = true;

        // Create an intent filter for when an NFC tag is discovered.  When
        // the NFC tag is discovered, Android will u
        var tagDetected = new IntentFilter(NfcAdapter.ActionTagDiscovered);
        var filters = new[] { tagDetected };

        // When an NFC tag is detected, Android will use the PendingIntent to come back to this activity.
        // The OnNewIntent method will invoked by Android.


        var intent = new Intent(this, GetType()).AddFlags(ActivityFlags.SingleTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);

        if (_nfcAdapter == null)
        {
            var alert = new AlertDialog.Builder(this).Create();
            alert.SetMessage("NFC is not supported on this device.");
            alert.SetTitle("NFC Unavailable");
            alert.SetButton("OK", delegate
                {
                    _writeTagButton.Enabled = false;
                    _textView.Text = "NFC is not supported on this device.";
                });
            alert.Show();
        }
        else
            _nfcAdapter.EnableForegroundDispatch(this, pendingIntent, filters, null);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="tag"></param>
    /// <param name="ndefMessage"></param>
    /// <returns></returns>
    private bool TryAndFormatTagWithMessage(Tag tag, NdefMessage ndefMessage)
    {
        var format = NdefFormatable.Get(tag);
        if (format == null)
        {
            DisplayMessage("Tag does not appear to support NDEF format.");
        }
        else
        {
            try
            {
                format.Connect();

                format.Format(ndefMessage);
                DisplayMessage("Tag successfully written.");


                return true;
            }
            catch (System.IO.IOException ioex)
            {
                var msg = "There was an error trying to format the tag.";
                DisplayMessage(msg);
                //Log.Error(Tag, ioex, msg);
            }
        }
        return false;
    }


    private void WriteTagButtonOnClick(object sender, EventArgs eventArgs)
    {
        var view = (View)sender;
        if (view.Id == Resource.Id.write_tag_button)
        {
            DisplayMessage("Touch and hold the tag against the phone to write.");
            EnableWriteMode();
        }

        if (view.Id == Resource.Id.btnLoadCash)
        {

            if (_textAmount.Text.Trim().Length == 0)
                toast("Please enter Amount.");
            else
            {
                if (_textCard.Text.Trim().Length == 0)
                {
                    toast("Please enter Card Number");
                    return;
                }

                amount = 0;

                try
                {
                    amount = Convert.ToDouble(_textAmount.Text.Trim());
                }
                catch
                {
                    toast("Invalid Amount");
                    return;
                }

                if (cardID == "")
                    cardID = _textCard.Text;

                balance += amount;
                DisplayMessage("Touch and hold the tag against the phone to write.");
                EnableWriteMode();
            }




        }
        if (view.Id == Resource.Id.btnSale) {
            DisplayMessage("Touch and hold the tag against the phone to write.");
            EnableWriteMode();
        }
    }


    /// <summary>
    /// This method will try and write the specified message to the provided tag. 
    /// </summary>
    /// <param name="tag">The NFC tag that was detected.</param>
    /// <param name="ndefMessage">An NDEF message to write.</param>
    /// <returns>true if the tag was written to.</returns>
    private bool TryAndWriteToTag(Tag tag, NdefMessage ndefMessage)
    {

        // This object is used to get information about the NFC tag as 
        // well as perform operations on it.
        var ndef = Ndef.Get(tag);
        if (ndef != null)
        {
            ndef.Connect();

            // Once written to, a tag can be marked as read-only - check for this.
            if (!ndef.IsWritable)
            {
                DisplayMessage("Tag is read-only.");
            }

            // NFC tags can only store a small amount of data, this depends on the type of tag its.
            var size = ndefMessage.ToByteArray().Length;
            if (ndef.MaxSize < size)
            {
                DisplayMessage("Tag doesn't have enough space.");
            }

            ndef.WriteNdefMessage(ndefMessage);
            DisplayMessage("Succesfully wrote tag.");
            return true;
        }

        return false;
    }
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用Android.App;
使用Android.Content;
使用Android.OS;
使用Android.Runtime;
使用Android.Views;
使用Android.Widget;
使用Android.Nfc;
使用Android.Nfc.Tech;
使用Android.Preferences;
使用Java.IO;
使用System.Threading.Tasks;
使用System.Net.Http;
使用System.Runtime.Serialization.Formatters.Binary;
使用System.IO;
命名空间[已删除]
{
[活动(Label=“更新卡”)]
公共类NFC编写器:活动
{
公共静态只读字符串首选项_FILENAME=“[removed]”;
公共静态只读字符串CLIENTID=“CLIENTID”;
公共静态只读字符串CLIENTUSERID=“CLIENTUSERID”;
公共静态只读字符串EMAILADDRESS=“EMAILADDRESS”;
公共静态只读字符串cardd=“cardd”;
公共静态只读字符串USERID=“USERID”;
公共静态只读字符串BALANCE=“BALANCE”;
public const string ViewApeMimeType=“application/[removed]”;//“application/[removed]”;
私有bool_inWriteMode;
私人NfcAdapter\u NfcAdapter;
私有文本视图_TextView;
专用按钮_writeTagButton;
私人自动完成文本视图_textmail;
公共静态只读字符串Tag=“NFC Writer”;
公共静态字符串uuid=“”;
私有文本视图_textCard;
私有编辑文本_textAmount;
私有静态串梳理器;
私人静态双平衡;
私有静态双新平衡;
私人文本视图(txtCard),;
私有文本视图xtbalance;
私有文本视图(txtu txtProduct);
私有文本视图txtotalprice;
私有静态字符串布局;
私人双倍金额=0.0f;
创建时受保护的覆盖无效(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var c=(上下文)这个;
//获取nfc设备适配器
_nfcAdapter=nfcAdapter.GetDefaultAdapter(此);
var allxsSettings=c.getSharedReferences(首选项文件名,FileCreationMode.Private);
layout=allxsSettings.GetString(“布局”、“注册”);
如果(布局=“注册”)
{
SetContentView(Resource.Layout.writer);
if(Intent==null)
{
返回;
}
_writeTagButton=FindViewById(Resource.Id.write_标记_按钮);
_writeTagButton。单击+=writeTagButton取消单击;
_textView=findviewbyd(Resource.Id.text\u视图);
_textmail=findviewbyd(Resource.Id.EmailID);
_textmail.Text=”“;
}
如果(布局=“现金负载”)
{
//_inWriteMode=true;
SetContentView(Resource.Layout.LoadCash);
if(Intent==null)
{
返回;
}
_writeTagButton=FindViewById(Resource.Id.btnLoadCash);
_writeTagButton。单击+=writeTagButton取消单击;
_textView=findviewbyd(Resource.Id.text\u视图);
_textAmount=FindViewById(Resource.Id.txtCash);
_textCard=findviewbyd(Resource.Id.txtCardId);
cardID=allxsSettings.GetString(cardID,“”);
var tempBalance=allxsSettings.GetFloat(BALANCE,0.0f);
balance=转换为双字节(tempBalance);
_textCard.Text=cardd;
_textmount.Text=”“;
}
如果(布局=“销售”){
//_inWriteMode=true;
SetContentView(Resource.Layout.Sale);
if(Intent==null)
{
返回;
}
_writeTagButton=FindViewById(Resource.Id.btnSale);
_writeTagButton。单击+=writeTagButton取消单击;
_textView=findviewbyd(Resource.Id.text\u视图);
_txtBalance=findviewbyd(Resource.Id.txtCash);
_txtCard=findviewbyd(Resource.Id.txtCardId);
_txtProduct=findviewbyd(Resource.Id.txtProduct);
_txtTotalPrice=FindViewById(Resource.Id.txtPrice);
cardID=allxsSettings.GetString(cardID,“”);
var tempBalance=allxsSettings.GetFloat(平衡,0.0f);
balance=转换为双字节(tempBalance);
_Text=cardd;
_txtBalance.Text=balance.ToString(“0.00”);
productRow=null;
小数总数=0;
_txtProduct.Text=“”;
foreach(SalesManager.GetSaless()中的var salesRow){
productRow=ProductManager.GetProduct(salesRow.ProductID);
totalAmount+=Convert.ToDecimal(salesRow.totalAmount);
如果(_txtProduct.Text.Length!=0)
_txtProduct.Text+=“\n”;
_txtProduct.Text+=salesRow.NoOfUnits+“x”+productRow.ProductName+“@”+productRow.UnitPrice.ToString(“0.00”);
}
_txtTotalPrice.Text=totalAmount.ToString(“0.00”);
//确定新卡的余额
newBalance=余额-转换为双倍(总金额);
如果(新平衡<0){
//我们没有
Android.Content.Intent intent = new Intent(Application.ApplicationContext, typeof(NfcWriter));
intent.AddFlags(ActivityFlags.NewTask);

StartActivity(intent);