我正在开发一个将使用 NFC 标签进行识别的应用程序。然而,我发现的所有示例都是关于在读取某张卡片时启动应用程序的。我尝试寻找有关如何以不同方式执行此操作的示例或文档,但无济于事。
我想要的是:
- 用户启动我的应用
- 用户扫描 NFC 卡
- 应用决定下一步
我现在有一些代码可以工作了,我只是没有得到标签数据:
在 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 仅在应用处于 Activity 状态时到达那里,但我收到的 Intent
是我自己定义的 PendingIntent
,而不是 ACTION_TECH_DISCOVERED
我想要的 Intent 。
最佳答案
我在这里找到了部分答案:NFC broadcastreceiver problem
该解决方案未提供完整的工作示例,因此我尝试了一些额外的操作。为了帮助 future 的访客,我将发布我的解决方案。它是一个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);
}
}
}
关于android - 只需读取 NFC 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16399662/