刚刚看了一个NFC标签 [英] Just read an NFC tag
问题描述
我开发一个应用程序,将使用NFC标签进行识别。然而,所有的例子我看到的是关于启动一个应用程序时,一定卡被读取。我试图寻找关于如何做到这一点不同,但没有成功的例子或文档。
I am developing an app that will use NFC tags for identification. All examples I find however, are about starting an app when a certain card is read. I tried looking for an example or documentation on how to do it differently, to no avail.
我要的是:
- 在用户启动我的应用程序
- 在用户扫描NFC卡
- 应用程序决定下一步
我得到了一些code现在的工作,我只是不明白的标签数据:
I got some code working now, I just don't get the tag data:
在的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);
这样做的目的只有到达那里时,应用程序处于活动状态,但意图
我收到的是 PendingIntent
我定义我自己,而不是 ACTION_TECH_DISCOVERED
意图我想要的。
The intent only gets there when the app is active, but the Intent
I receive is the PendingIntent
I defined myself, not the ACTION_TECH_DISCOVERED
intent I want.
推荐答案
我找到了部分答案: NFC BroadcastReceiver的问题
这是解决方案并没有提供一个完整的工作的例子,所以我尝试了一些钱。为了帮助未来的访客,我会后我的解决办法。这是一个 NfcActivity
其子类活动
,如果将此类子 NfcActivity
,所有你所要做的就是实现它 NfcRead
方法,你是好去:
That solution doesn't provide a complete working example, so I tried a little extra. To help future visitors, I'll post my solution. It is a NfcActivity
which subclasses Activity
, if you subclass this NfcActivity
, all you have to do is implement its NfcRead
method, and you're good to go:
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标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!