android - 只需读取 NFC 标签

标签 android nfc

我正在开发一个将使用 NFC 标签进行识别的应用程序。然而,我发现的所有示例都是关于在读取某张卡片时启动应用程序的。我尝试寻找有关如何以不同方式执行此操作的示例或文档,但无济于事。

我想要的是:

  1. 用户启动我的应用
  2. 用户扫描 NFC 卡
  3. 应用决定下一步

我现在有一些代码可以工作了,我只是没有得到标签数据:

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/

相关文章:

android - 无法在OS X中添加多个环境路径

java - 如何将字符串转换为 const 类 int 值?

android - 由于 RECEIVE_SMS 权限被拒绝,Cordova Android 应用程序在 Android P 上崩溃

ios - Ionic,iOS 中的 phonegap nfc 异常

nfc - Nexus 7 2012 上的主机卡仿真

android - 在 Kotlin Android 中使用 NumberFormat.getCurrency

Android加速度计类

android - 寻找 PN544 NFC 芯片的用户手册或 eeprom 指令集

nfc - 禁用 ACR122U 上的默认红色 LED

android - NFC - 写入 MiFare Classic 1K