當前應用攔截NFC響應,不彈出選擇框教程

從上一篇的NFC支持所類型的卡讀取之後,下面要解決的就是NFC的攔截響應,如果這一步沒有做,當系統內有多個支持NFC的應用的時候,就會在nfc刷卡的時候彈出多個應用選擇,我們需要的場景是,當前應用需要用NFC纔去刷卡,然後本應用攔截intent分發(Using the Foreground Dispatch System).

具體的方案:

1.創建PendingIntent來分發要響應的Activity

  1. mPendingIntent = PendingIntent.getActivity(this0,  
  2.               new Intent(this, NFCActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);  

2.當刷卡的時候,使用intent過濾器來過濾出你要攔截的Intent

  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數組中

  1. techListsArray = new String[][]{new String[]{NfcA.class.getName()}};  

4.在onResume和onPause中設置NFCAdapter

  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

 

  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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章