2012-09-07 66 views
1

嗨我想從NFC標籤讀取。但我得到一個例外。如何閱讀NFC標籤?

我已經把這個條件來檢測標籤?

if(NfcAdapter.ACTION_TAG_DISCOVERED != null) 

此條件是否正確?

+0

這裏難以理解請詳細說明 –

+0

當我將手機接近標籤時,必須檢測標籤。那麼我應該使用什麼條件來觸發標記檢測事件 – ssg

回答

2

回答您有關代碼的問題 -

,將永遠是真實的 - NfcAdapter.ACTION_TAG_DISCOVERED是一個恆定值 - 你需要使用:

getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED) 

來進行比較。

但是,這可能無關,與你的例外 -

  1. 沒有您在您的Android清單的NFC允許嗎?
  2. 你確定你的手機支持NFC,但目前只有兩個或三個支持NFC。
  3. 我們需要從日誌堆棧跟蹤知道是什麼引起的異常
+0

我正在檢查onStart()方法中的條件。是否與異常有關 – ssg

+0

試試這個[樣板](http://code.google.com/p/nfc-eclipse-plugin/downloads/list) – ThomasRS

1

該聲明將永遠是正確的。

我已經創建了一個​​,它有一個模板項目,可以幫助您走上正確的軌道。

3

首先你必須初始化NFC適配器和回調的onCreate定義待定意向:

NfcAdapter mAdapter; 
PendingIntent mPendingIntent; 
mAdapter = NfcAdapter.getDefaultAdapter(this);  

    if (mAdapter == null) { 
     //nfc not support your device. 
     return; 
    } 
    mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, 
      getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 

在的onResume()回撥使前景調度來檢測NFC意圖。

mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null); 

在的onPause()回調必須禁用於地面調度:

if (mAdapter != null) { 
     mAdapter.disableForegroundDispatch(this); 
    } 

在onNewIntent()回調方法,你會得到新的NFC意向。得到的意圖後,你必須分析的意圖來檢測卡:

@Override 
protected void onNewIntent(Intent intent){  
    getTagInfo(intent) 
    } 

private void getTagInfo(Intent intent) { 
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 

String[] techList = tag.getTechList(); 
for (int i = 0; i < techList.length; i++) { 
    if (techList[i].equals(MifareClassic.class.getName())) { 

     MifareClassic mifareClassicTag = MifareClassic.get(tag); 
     switch (mifareClassicTag.getType()) { 
     case MifareClassic.TYPE_CLASSIC: 
      //Type Clssic 
      break; 
     case MifareClassic.TYPE_PLUS: 
      //Type Plus 
      break; 
     case MifareClassic.TYPE_PRO: 
      //Type Pro 
      break; 
     } 
    } else if (techList[i].equals(MifareUltralight.class.getName())) { 
    //For Mifare Ultralight 
     MifareUltralight mifareUlTag = MifareUltralight.get(tag); 
     switch (mifareUlTag.getType()) { 
     case MifareUltralight.TYPE_ULTRALIGHT: 
      break; 
     case MifareUltralight.TYPE_ULTRALIGHT_C: 

      break; 
     } 
    } else if (techList[i].equals(IsoDep.class.getName())) { 
     // info[1] = "IsoDep"; 
     IsoDep isoDepTag = IsoDep.get(tag); 

    } else if (techList[i].equals(Ndef.class.getName())) { 
     Ndef.get(tag); 

    } else if (techList[i].equals(NdefFormatable.class.getName())) { 

     NdefFormatable ndefFormatableTag = NdefFormatable.get(tag); 

    } 
} 
} 

全部完整代碼here