Я пытаюсь считать данные с карты NFC. Я использую следующие функции для получения и чтения сообщения NDEF
, однако получаю нулевое сообщение.
Я могу получить правильную длину данных с помощью getMaxSize()
, а getType()
возвращает org.nfcforum.ndef.type2
, но функция getCachedNdefMessage()
возвращает значение null. Более того, я получаю android.nfc.action.TAG_DISCOVERED
как намерение вместо ACTION_NDEF_DISCOVERED
.
@Override
protected void onResume() {
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};
String [][] techListsArray = new String[][]{new String[]{
Ndef.class.getName()
}};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(mNfcAdapter!= null) {
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
else {
Log.d(TAG, "NFC not supported.");
}
}
@Override
protected void onPause() {
super.onPause();
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent: "+intent.getAction());
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
printTagId(intent);
if(tag != null) {
Log.d(TAG, "TAG detected.");
String [] tagList = tag.getTechList();
if(tagList != null)
{
for (String str : tagList) {
Log.d(TAG, "Tech " + str);
}
}
Ndef ndef = Ndef.get(tag);
readNDef(ndef);
}
else {
Log.d(TAG, "TAG is null.");
}
}
private void readNDef(Ndef ndef) {
try {
ndef.connect();
Log.d(TAG, "ndef type: " + ndef.getType());
Log.d(TAG, "ndef maxSize: " + ndef.getMaxSize());
Log.d(TAG, "ndef isWritable: " + ndef.isWritable());
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
if(ndefMessage != null && ndefMessage.getRecords().length > 0) {
String message = new String(ndefMessage.getRecords()[0].getPayload());
Log.d(TAG, "readNDef: " + message);
}
else{
Log.d(TAG, "readNDef: NO Records.");
}
ndef.close();
} catch (Exception e) {
Log.d(TAG, "readNDef exception!");
e.printStackTrace();
}
try{ if(ndef != null) ndef.close(); } catch (Exception ex){}
}
И вывод выглядит следующим образом:
onNewIntent: android.nfc.action.TAG_DISCOVERED
Tech android.nfc.tech.MifareUltralight
Tech android.nfc.tech.NfcA
Tech android.nfc.tech.Ndef
ndef type: org.nfcforum.ndef.type2
ndef maxSize: 1908
ndef isWritable: true
readNDef: NO Records.
Когда я читаю данные NDEF с помощью другого бесплатного приложения, я уверен, что на карте есть данные типа NDEF. Я не могу понять, почему я не получаю ACTION_NDEF_DISCOVERED
вместо TAG_DISCOVERED
. Как я могу получить данные в формате NDEF?