2012-09-07 166 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