從上一篇的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.