【发布时间】:2016-11-29 17:58:20
【问题描述】:
我有一个正在读取 NFC 标签的 xamarin 应用程序。应用程序打开时它工作正常,但如果应用程序在后台或关闭,则无法从标签中读取数据。
我的意图过滤器:
[IntentFilter(
new[] {"android.nfc.action.NDEF_DISCOVERED", "android.intent.action.VIEW", "android.intent.action.MAIN"},
Categories =
new[]
{
"android.intent.category.DEFAULT", "android.intent.category.BROWSABLE",
"android.intent.category.LAUNCHER"
},
DataScheme = "http", DataHost = "app.myDomain.com")]
在我的 OnNewIntent 中,从应用程序外部扫描时,我的 intent.Data 始终返回为 null。对我的问题可能出在哪里有任何想法?
恢复:
nfcAdapter.EnableForegroundDispatch(this, nfcPendingIntent, nfcIntentFiltersArray, null);
OnNewIntent:
protected override void OnNewIntent(Intent intent)
{
if (AndroidNFCHelper.isNfcIntent(intent))
{
DisplayMessage("And it is an NFC intent");
}
var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
if (tag == null)
{
Debug.WriteLine("tag is null");
return;
}
//rest of OnNewIntent code...
}
所以有趣的是,当在应用程序外部扫描时,AndroidNFCHelper.isNfcIntent 返回为 false。当在应用程序中扫描相同的 NFC 标签时,它会返回为真。继续,标签最终为 null 并且只是命中 return 语句。在应用中扫描时,标签不为空并继续。
PrepareForegroundNFCHandling - 在 OnCreate() 中调用:
private void PrepareForegroundNFCHandling()
{
var tagDetected = new IntentFilter(NfcAdapter.ActionTagDiscovered);
var ndefDetected = new IntentFilter(NfcAdapter.ActionNdefDiscovered);
nfcIntentFiltersArray = new[] { ndefDetected, tagDetected};
var intent = new Intent(this, GetType()).AddFlags(ActivityFlags.SingleTop | ActivityFlags.BroughtToFront);
nfcPendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
nfcAdapter = NfcAdapter.GetDefaultAdapter(Application.ApplicationContext);
}
【问题讨论】:
-
您在标签上存储了哪些数据(NDEF 消息)?在您的应用关闭(或在后台)时点击标签是否会导致您的活动被打开?您在 OnCreate()、OnStart()、OnResume() 中有哪些代码?你在 OnNewIntent() 中看到了什么 intent.Action?
-
它只是一个 url.. 类似app.myDomain.com/p/9。在关闭应用程序的情况下点击确实会打开应用程序,但由于标记对象最终返回 null,因此什么也没有发生。我会用其他代码更新帖子
-
您是否从代码中的任何位置调用 OnNewIntent()?您确定您的标签仅包含一个带有 URL 的 NDEF 记录,并且它不包含带有您的应用程序包名称的 Android 应用程序记录吗?
-
所以我能够解决这个问题......最终我的 nfc 标签被编码为包名作为记录 0,url 作为记录 1。我将它们翻转过来,它神奇地开始工作...
标签: xamarin xamarin.android nfc ndef android-applicationrecord