只需阅读NFC标签
我正在开发一款将使用NFC标签进行识别的应用程序。然而,我发现的所有例子都是关于在读取特定卡片时启动应用程序。我试着寻找一个例子或文件来说明如何以不同的方式做到这一点,但都无济于事。只需阅读NFC标签
我要的是:
- 用户开始我的应用程序
- 用户扫描NFC卡
- 应用决定下一步
我得到了一些代码,现在的工作,我只是不” t获取标签数据:
In onCreate
:
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
try {
tech.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
intentFiltersArray = new IntentFilter[] { tech };
而且在onResume
:
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techList);
这样做的目的只有到达那里时,应用程序是积极的,但我收到Intent
是我定义自己的PendingIntent
,而不是ACTION_TECH_DISCOVERED
意图我想要的。
我在这里找到了部分答案:NFC broadcastreceiver problem
这种解决方案并没有提供一个完整的工作示例,所以我尝试了一些钱。为了帮助未来的访问者,我会发布我的解决方案。这是一个NfcActivity
其子类Activity
,如果将此类子NfcActivity
,所有你所要做的就是实现它的方法NfcRead
,你是好去:
public abstract class NfcActivity extends Activity {
// NFC handling stuff
PendingIntent pendingIntent;
NfcAdapter nfcAdapter;
@Override
public void onResume() {
super.onResume();
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
@Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
// does nothing, has to be overridden in child classes
public abstract void NfcRead(Intent intent);
@Override
public void onNewIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
NfcRead(intent);
}
}
}
如果你想让用户第一次启动你的应用程序,然后只扫描NFC卡,我会建议使用NFC foreground dispatch。这样,您的活动不需要在清单中有任何意图过滤器(因此当用户扫描另一张NFC卡时不会意外调用)。 启用前台调度功能后,您的活动可以直接接收所有NFC意图(无需任何应用程序选择器弹出窗口),并决定如何处理它(例如将它传递给其他活动)。
是的,我发现有些事情可以做到这一点。我现在的问题是'Intent'工作正常(当我的'Activity'处于活动状态时收到它,并且它不会从主屏幕启动应用程序),我只是没有获得任何NFC数据。 – 2013-05-06 14:27:34
你的意思是什么“NFC数据”?一个'Tag'对象或一个'NdefMessage'? – 2013-05-06 14:37:19
一个'标记'对象。但我现在找到了。我重写了'OnNewIntent'方法,但由于某种原因它没有被调用。我将过滤器和技术列表更改为“空”,现在可以工作。 – 2013-05-06 14:38:37
@ njzk2标准的例子,其注册一个'的IntentFilter在清单中。他们工作,但他们不做我想要的。当然还有很多互联网搜索。 – 2013-05-06 13:28:42
显然你应该注册你的活动,如果你想阅读nfc。我没有看到任何直接从中读取的方法。但是,您可以将标签的处理置于仅在阅读时才能运行的条件块中。 (不知道如果标签已经在范围内会发生什么) – njzk2 2013-05-06 14:15:01