从上一篇的NFC支持所类型的卡读取之后,下面要解决的就是NFC的拦截响应,如果这一步没有做,当系统内有多个支持NFC的应用的时候,就会在nfc刷卡的时候弹出多个应用选择,我们需要的场景是,当前应用需要用NFC才去刷卡,然后本应用拦截intent分发(Using the Foreground Dispatch System).
具体的方案:
1.创建PendingIntent来分发要响应的Activity
- mPendingIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, NFCActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
2.当刷卡的时候,使用intent过滤器来过滤出你要拦截的Intent
- IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
- try {
- ndef.addDataType("*/*");
- } catch (IntentFilter.MalformedMimeTypeException e) {
- throw new RuntimeException("fail", e);
- }
- intentFiltersArray = new IntentFilter[]{ndef,};
3.设置你要处理的tag technologies到String数组中
- techListsArray = new String[][]{new String[]{NfcA.class.getName()}};
4.在onResume和onPause中设置NFCAdapter
- public void onPause() {
- super.onPause();
- mAdapter.disableForegroundDispatch(this);
- }
- public void onResume() {
- super.onResume();
- mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
- }
- nfcAdapter = NfcAdapter.getDefaultAdapter(this);
里面的链接指向的是Android develop。。。NFC foreground dispatching.