当前应用拦截NFC响应,不弹出选择框教程

从上一篇的NFC支持所类型的卡读取之后,下面要解决的就是NFC的拦截响应,如果这一步没有做,当系统内有多个支持NFC的应用的时候,就会在nfc刷卡的时候弹出多个应用选择,我们需要的场景是,当前应用需要用NFC才去刷卡,然后本应用拦截intent分发(Using the Foreground Dispatch System).

具体的方案:

1.创建PendingIntent来分发要响应的Activity

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. mPendingIntent = PendingIntent.getActivity(this0,  
  2.               new Intent(this, NFCActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);  

2.当刷卡的时候,使用intent过滤器来过滤出你要拦截的Intent

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);  
  2.       try {  
  3.           ndef.addDataType("*/*");  
  4.       } catch (IntentFilter.MalformedMimeTypeException e) {  
  5.           throw new RuntimeException("fail", e);  
  6.       }  
  7.       intentFiltersArray = new IntentFilter[]{ndef,};  

3.设置你要处理的tag technologies到String数组中

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. techListsArray = new String[][]{new String[]{NfcA.class.getName()}};  

4.在onResume和onPause中设置NFCAdapter

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public void onPause() {  
  2.     super.onPause();  
  3.     mAdapter.disableForegroundDispatch(this);  
  4. }  
  5.   
  6. public void onResume() {  
  7.     super.onResume();  
  8.     mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);  
  9. }  
当然之前要定义NfcAdapter

 

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. nfcAdapter = NfcAdapter.getDefaultAdapter(this);  
这个问题的解决体会到一件事,这个问题在国内的博客论坛都没有搜索到,在StackOverFlow上有一篇

http://stackoverflow.com/questions/16542147/how-to-read-nfc-tags-to-prevent-system-dialogs-nfc-starter-list-and-tags-being-d

里面的链接指向的是Android develop。。。NFC foreground dispatching

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值