我正在开发应用程序来演示 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());
}
谢谢大家:)
最佳答案
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.android - 如何通过 Xamarin.Android 使用 NFC 发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66098988/