【问题标题】:How do you send message using NFC with Xamarin.Android?如何使用 NFC 和 Xamarin.Android 发送消息?
【发布时间】:2021-05-11 21:40:47
【问题描述】:

我正在开发应用程序来演示 NFC 的工作原理。我的目标是制作与 Android Beam 非常相似的应用程序。我正在使用 Xamarin.Android。目标是在一个设备上输入消息,按下按钮,它应该被发送到另一台具有相同应用程序的设备上。我几乎尝试了所有东西,甚至是文档,但似乎它不起作用。有人对这项技术有任何经验吗?现在还有这种技术吗?

我的一些代码可以让你了解我想要做什么:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        mNfcAdapter = NfcAdapter.GetDefaultAdapter(this);


        myButton.Click += (e, o) => { 
            mNfcAdapter.SetNdefPushMessageCallback(this, this);
            mNfcAdapter.SetOnNdefPushCompleteCallback(this, this);
            };
    }

   public NdefMessage CreateNdefMessage(NfcEvent e)
    {
        DateTime time = DateTime.Now;
        var text = (time.ToString("HH:mm:ss") + message2);
        NdefMessage msg = new NdefMessage(
        new NdefRecord[] { CreateMimeRecord (
            text, Encoding.UTF8.GetBytes (text))});
        return msg;
    }

    private NdefRecord CreateMimeRecord(string mimeType, byte[] payload)
    {
        byte[] mimeBytes = Encoding.UTF8.GetBytes(mimeType);
        NdefRecord mimeRecord = new NdefRecord(
            NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
        return mimeRecord;
    }

    public void OnNdefPushComplete(NfcEvent e)
    {
        Toast.MakeText(this.ApplicationContext, "Message sent", ToastLength.Long).Show();
    }

    protected override void OnResume()
    {
        base.OnResume();
        if (NfcAdapter.ActionNdefDiscovered == Intent.Action)
        {
            ProcessIntent(Intent);
        }
    }

    protected override void OnNewIntent(Intent intent)
    {
        Intent = intent;
    }

    void ProcessIntent(Intent intent)
    {
        IParcelable[] rawMsgs = intent.GetParcelableArrayExtra(
            NfcAdapter.ExtraNdefMessages);
        NdefMessage msg = (NdefMessage)rawMsgs[0];
        var textViewMsg = FindViewById<TextView>(Resource.Id.textViewMsg);
        textViewMsg.Text = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload());
    }

谢谢大家:)

【问题讨论】:

  • 您在哪个 Android 版本(两部手机)上运行此功能?
  • 一个有Android 11,另一个有8

标签: xamarin.android nfc ndef


【解决方案1】:

OnNdefPushComplete 和整个 Android Beam 已被弃用并从 Android 10 中删除

https://developer.android.com/reference/android/nfc/NfcAdapter.OnNdefPushCompleteCallback

如果您想继续进行设备到设备 NFC,那么应该可以使用一部手机进行主机卡仿真 (HCE),另一部使用 enableReaderMode

但 Google 建议使用蓝牙或 Wifi Direct 作为 Android Beam 的更可靠替代品。 Google 提供的替代方法之一是 Android Nearby https://developers.google.com/nearby

【讨论】:

  • 哇,谢谢。这实际上真的很有帮助。所以我需要两个应用程序来做到这一点?或者我可以在一个应用程序中拥有它吗? :)
  • 嘿,打扰了。但是您知道有关使用 Xamarin 的 HCE 的任何示例吗?我发现的那个真的已经过时了,我无法让它工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 2013-03-26
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
相关资源
最近更新 更多