如何显示十六进制唯一 ID NFC 标签在我的安卓 NFC 应用程序中?



我已经做了一个可以工作查找的写标签应用程序,我将数据文本存储在NFC标签中的标记事物(例如:计算机1(。写入和读取都工作正常。但是当我阅读我知道具有唯一十六进制 ID 的信息文本时,我需要读取每个标签都具有的十六进制 ID(因为我在那里使用 google play 应用程序测试它时看到了那个(。但我不知道该怎么做。我真的很不擅长编码,所以请帮助我。

这是代码:

public class MainActivity extends Activity {
NfcAdapter mAdapter;
Tag mTag;
PendingIntent mPI;
IntentFilter mFilter[]; 
String userData,yo;
boolean writeMode;
Context context;
TextView tvNFCContent, Timer,Low;
Button start, pause, reset, lap ;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
Handler handler;
int Seconds, Minutes, MilliSeconds ;
ListView listView ;
String[] ListElements = new String[] {  };
List<String> ListElementsArrayList ;
ArrayAdapter<String> adapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvNFCContent = (TextView) findViewById(R.id.data);
Timer = (TextView)findViewById(R.id.timer);
tvNFCContent.addTextChangedListener(watch);
handler = new Handler() ;
mAdapter = NfcAdapter.getDefaultAdapter(this);
mPI = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilter = new IntentFilter[]{tagDetected,filter2};
mAdapter = NfcAdapter.getDefaultAdapter(this);
if (mAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
}

private void readFromIntent(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)) 
{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}                               
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}

tvNFCContent.setText("NFC Content: " + text);
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
}  
NdefMessage[] getNdefMessage(Intent intent)
{
NdefMessage[] msgs = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(rawMsgs != null)
{
msgs = new NdefMessage[rawMsgs.length];
for(int i=0; i<rawMsgs.length; i++)
{
msgs[i] = (NdefMessage)rawMsgs[i];
}
}
return msgs;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub

setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
super.onNewIntent(intent);
if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{           
Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();
}else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
{
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
NdefMessage[] messages = getNdefMessage(intent);            
if(messages == null)
{
Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
return;
}           
byte[] payload = messages[0].getRecords()[0].getPayload();          
userData = new String(payload);
} else { 
Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
}
}   
public Runnable runnable = new Runnable() {
public void run() {
MillisecondTime = SystemClock.uptimeMillis() - StartTime;
UpdateTime = TimeBuff + MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
Timer.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);
}
TextWatcher watch = new TextWatcher(){
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int a, int b, int c) {
// TODO Auto-generated method stub
}
};
}

很抱歉我上传了整个代码,我只是想让任何想帮助我的人都变得容易。

将此代码添加到 onNewIntent(( 中

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] uid = tag.getId(); //This is the Unique IDentifier of the card

使用以下方法获取十六进制值

public static String getHexValue(final byte[] buffer) {
if (buffer == null || buffer.length == 0) {
return ("0x" + "[none]");
}
final StringBuffer sb = new StringBuffer();
sb.append("0x");
for (int i = 0; i < buffer.length - 1; i++) {
sb.append(String.format("%02X%s", buffer[i], ""));
}
sb.append(String.format("%02X", buffer[buffer.length - 1]));
return sb.toString();
}

我终于可以做到了。感谢所有帮助过我的人。这是我与您分享的完整代码。

package com.nfcreadfull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.List;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {

NfcAdapter mAdapter;
Tag mTag;
PendingIntent mPI;
IntentFilter mFilter[]; 
String userData,yo;
boolean writeMode;
Context context;
TextView tvNFCContent, Timer,Low, Uid;

Button start, pause, reset, lap ;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
int Seconds, Minutes, MilliSeconds ;
ListView listView ;
String[] ListElements = new String[] {  };
List<String> ListElementsArrayList ;
ArrayAdapter<String> adapter ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tvNFCContent = (TextView) findViewById(R.id.data);
Timer = (TextView)findViewById(R.id.timer);
Uid = (TextView)findViewById(R.id.uid); 
mAdapter = NfcAdapter.getDefaultAdapter(this);
mPI = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilter = new IntentFilter[]{tagDetected,filter2};

mAdapter = NfcAdapter.getDefaultAdapter(this);
if (mAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
}

private void readFromIntent(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)) 

{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];

}
}                               
buildTagViews(msgs);
}

}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}

tvNFCContent.setText("NFC Content: " + text);
}  

NdefMessage[] getNdefMessage(Intent intent)
{
NdefMessage[] msgs = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(rawMsgs != null)
{
msgs = new NdefMessage[rawMsgs.length];
for(int i=0; i<rawMsgs.length; i++)
{
msgs[i] = (NdefMessage)rawMsgs[i];
}
}
return msgs;
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
Uid.setText(ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));


setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
super.onNewIntent(intent);
if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{           
Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();
}else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
{
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage[] messages = getNdefMessage(intent);            
if(messages == null)
{
Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
return;
}           
byte[] payload = messages[0].getRecords()[0].getPayload();          
userData = new String(payload);

}else
{
Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
}


if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
// While with ForegroundDispatch the NDEF message has already been read
// And passed to us in the intent and thus the time the App spends "read" the NFC card is Zero
// We want to time time the read, so now we have been notified that a NDEF card is in range
// Try and read from it
// Get the Tag from the intent
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
long startTime = 0;
long endTime = 0;
try {
// Create an NDEF tag object
Ndef ndefTag = Ndef.get(tag);
// This is the I/O operation to read the card and format the result to an NDEF message
// Nothing is done with the result to not add any time to it, as we are timing this
startTime = System.currentTimeMillis();
ndefTag.connect();
ndefTag.getNdefMessage();
endTime = System.currentTimeMillis();
ndefTag.close();
} catch (Exception e) {
Log.e("NFC", e.toString());
}
MillisecondTime = endTime - startTime;
UpdateTime = MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
Timer.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + "."
+ String.format("%03d", MilliSeconds));

//Log.v("NFC", "Time to read in milliseconds is: " + (endTime - startTime));
//Timer.setText("00:00:0.0"+(endTime - startTime));
}
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();   
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefDetected.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {}
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(mAdapter!= null)
mAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

}

private String getHex(byte[] bytes) {
if (bytes == null) {
return null;
}
char[] hexChars = new char[bytes.length * 2];
final char[] hexArray = "0123456789abcdef".toCharArray();
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private long getDec(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 String ByteArrayToHexString(byte [] inarray) {
Log.d("ByteArrayToHexString", inarray.toString());
int i, j, in;
String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String out= "";
for(j = 0 ; j < inarray.length ; ++j)
{
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));

return out;
}

}

最新更新