【发布时间】:2012-09-07 07:24:17
【问题描述】:
您好,我正在尝试读取 NFC 标签。但我遇到了一个例外。
我已经设置了这个条件来检测标签?
if(NfcAdapter.ACTION_TAG_DISCOVERED != null)
这个条件是否正确?
【问题讨论】:
-
这里比较难理解请详细说明
-
当我将手机带到标签附近时,它必须检测到标签。那么我应该使用什么条件来触发标签检测事件
您好,我正在尝试读取 NFC 标签。但我遇到了一个例外。
我已经设置了这个条件来检测标签?
if(NfcAdapter.ACTION_TAG_DISCOVERED != null)
这个条件是否正确?
【问题讨论】:
首先你必须初始化 NFC 适配器并在 onCreate 回调中定义 Pending Intent:
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() 回调中启用 Foreground Dispatch 以检测 NFC 意图。
mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
在 onPause() 回调中,您必须禁用前台调度:
if (mAdapter != null) {
mAdapter.disableForegroundDispatch(this);
}
在 onNewIntent() 回调方法中,您将获得新的 Nfc Intent。获取到 Intent 后,需要解析 Intent 来检测卡片:
@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。
【讨论】:
回答你关于代码的问题-
这将永远是正确的 - NfcAdapter.ACTION_TAG_DISCOVERED 是一个常量值 - 你需要使用:
getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)
比较一下。
但是,这可能与您的异常无关 -
【讨论】:
那句话永远是正确的。
我创建了一个project,其中包含一个样板项目,以便走上正轨。
【讨论】:
试试下面的工作代码。
/**
* this method is used for read nfc data from tag.
*
* @param ndef Ndef
*/
private void readFromNFC(Ndef ndef) {
try {
ndef.connect();
NdefMessage ndefMessage = ndef.getNdefMessage();
NdefRecord[] e = ndefMessage.getRecords();
for (NdefRecord s : e) {
String message = new String(s.getPayload());
if (!message.equals("")) {
CustomLog.info(TAG, "readFromNFC: " + message);
mTvMessage.setText(message);
} else {
mTvMessage.setText("Tag is empty!");
}
}
ndef.close();
} catch (IOException | FormatException e) {
e.printStackTrace();
}
}
【讨论】: