ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

android – 只需阅读一个NFC标签

2019-07-25 16:25:51  阅读:165  来源: 互联网

标签:android nfc


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

我想要的是:

>用户启动我的应用程序
>用户扫描NFC卡
> app决定下一步

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

在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意图.

解决方法:

我在这里找到了部分答案: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);            
        } 
    }
}

标签:android,nfc
来源: https://codeday.me/bug/20190725/1534591.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有