Bonjour, je suis actuellement en train de développer une application permettant de lire des puce NFC pour en extraire le contenu, actuellement j'arrive à lire les différentes information du tag, dès que j'essaie d'extraire les données contenues mon application plante, auriez-vous une idée ?
Je vous remercie sincèrement du temps que vous pourriez m'accorder.
je vous transmet mon code actuelle avec en commentaire mes différents tests.
package com.example.tp_nfc;
import static android.content.ContentValues.TAG;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
NfcAdapter nfcAdapter;
TextView textView;
TextView ScrolledTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
textView = (TextView) findViewById(R.id.textView);
ScrolledTextView = (TextView) findViewById(R.id.TEXT_STATUS_ID);
}
@Override
protected void onResume() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilter = new IntentFilter[]{};
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilter, null);
}
super.onResume();
}
@Override
protected void onPause() {
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
super.onPause();
}
@Override
protected void onNewIntent(Intent intent) {
// Permet de notifier la reconnaissance d'un TAG NFC
Toast.makeText(this, "NFC intent reçu!", Toast.LENGTH_LONG).show();
textView = (TextView) findViewById(R.id.textView);
textView.setText(textView.getText() + "\n" + formatTimeToFrance());
resolveIntent(intent);
super.onNewIntent(intent);
}
private void resolveIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(tag);
assert tag != null;
byte[] payload = detectTagData(tag).getBytes();
textView.setText(detectTagData(tag));
String Contenu = intent.getParcelableExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
doInBackground(tag);
// ScrolledTextView.setText(RectorContent(intent));
}
/* Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord relayrecord = ((NdefMessage) rawMsgs[0]).getRecords()[0];
String nfcData = new String (relayrecord.getPayload());
Toast.makeText(this, nfcData, Toast.LENGTH_SHORT).show();*/
}
private String detectTagData(Tag tag) {
StringBuilder sb = new StringBuilder();
byte[] id = tag.getId();
sb.append("ID (hex): ").append(toHex(id)).append('\n');
sb.append("ID (reversed hex): ").append(toReversedHex(id)).append('\n');
sb.append("ID (dec): ").append(toDec(id)).append('\n');
sb.append("ID (reversed dec): ").append(toReversedDec(id)).append('\n');
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech : tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech : tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
String type = "Unknown";
try {
MifareClassic mifareTag = MifareClassic.get(tag);
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
} catch (Exception e) {
sb.append("Mifare classic error: " + e.getMessage());
}
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
readTag(mifareUlTag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
Log.v("test", sb.toString());
return sb.toString();
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private long toDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private long toReversedDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = bytes.length - 1; i >= 0; --i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private String toReversedHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
// Cocorico
protected String formatTimeToFrance() {
long millis = System.currentTimeMillis();
return String.format("%02d:%02d:%02d", (TimeUnit.MILLISECONDS.toHours(millis) % 24) + 1,
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
}
public String readTag(MifareUltralight mifareUlTag) {
try {
mifareUlTag.connect();
byte[] payload = mifareUlTag.readPages(4);
return new String(payload, Charset.forName("US-ASCII"));
} catch (IOException e) {
Log.e(TAG, "IOException while reading MifareUltralight message...", e);
} finally {
if (mifareUlTag != null) {
try {
mifareUlTag.close();
} catch (IOException e) {
Log.e(TAG, "Error closing tag...", e);
}
}
}
return null;
}
protected String doInBackground(Tag... params) {
Tag tag = params[0];
Ndef ndef = Ndef.get(tag);
if (ndef == null) return null;
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
NdefRecord[] records = ndefMessage.getRecords();
for (NdefRecord ndefRecord : records) {
if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
try {
return readText(ndefRecord);
} catch (UnsupportedEncodingException e) {
Log.e(String.valueOf(TAG), "Unsupported Encoding", e);
}
} else if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_URI)) {
try {
return readText(ndefRecord);
} catch (UnsupportedEncodingException e) {
Log.e(String.valueOf(TAG), "Unsupported Encoding", e);
}
}
}
return null;
}
/* private String readText(NdefRecord record) throws UnsupportedEncodingException {
byte[] payload = record.getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? new String("UTF-8") : "UTF-16";
int languageCOdeLenght = payload[0] & 0063;
return new String(payload, languageCOdeLenght + 1, payload.length - languageCOdeLenght - 1, textEncoding);
}*/
/* protected void RectorContent(Intent intent) {
Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messages[i] = (NdefMessage) rawMessages[i];
}
}*/
}
}
Salut, tu devrais joindre la stacktrace également. Sans ça c’est compliqué d’avoir de l’aide sur un crash.
Lecture puce NFC
× Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
× Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.