3

我正在开发一个使用 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我收到的是PendingIntent我自己定义的,而不是ACTION_TECH_DISCOVERED我想要的意图。

4

2 回答 2

8

我在这里找到了部分答案:NFC广播接收器问题

该解决方案没有提供完整的工作示例,所以我尝试了一些额外的。为了帮助未来的访客,我将发布我的解决方案。它是NfcActivitywhich subclasses Activity,如果你继承 this 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);            
        } 
    }
}
于 2013-05-06T15:06:47.217 回答
2

如果您希望用户首先启动您的应用程序,然后才扫描 NFC 卡,我建议使用NFC 前台调度。这样,您的 Activity 不需要在清单中包含任何意图过滤器(因此当用户扫描另一张 NFC 卡时永远不会被意外调用)。启用前台调度后,您的 Activity 可以直接接收所有 NFC 意图(没有任何应用程序选择器弹出窗口)并决定如何处理它(例如将其传递给另一个 Activity)。

于 2013-05-06T14:19:55.527 回答