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

huangapple go评论78阅读模式
英文:

How to show Hexadecimal unique ID NFC Tag have in my android NFC application?

问题

public class MainActivity extends Activity {

    // ... (Other variable declarations and imports)

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

        // ... (Other initialization code)

        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 = "";
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
        int languageCodeLength = payload[0] & 0063;

        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);
    }

    // ... (Other methods and overrides)
    
    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);
        }
    };

    // ... (Other lifecycle methods)
}

Please note that this is a partial translation of the code provided, focusing on the main parts of the code related to NFC tag handling and timer functionality. If you need further assistance or have any specific questions about the code, feel free to ask.

英文:

I already make a write tag application that working find, I store data text to labeled thing ( example : computer 1) in NFC tag. Both write and read working fine. But I need to read the Hexadecimal ID that every tag have when I read the information text I know the have unique Hexadecimal ID (Cause I see that one when I test it with google play application there). But I don't know how to do it. I'm really bad at coding, so please help me.

Here is the code :

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&lt;String&gt; ListElementsArrayList ;
ArrayAdapter&lt;String&gt; 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, &quot;This device doesn&#39;t support NFC.&quot;, 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 &lt; rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}                               
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = &quot;&quot;;
//        String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] &amp; 128) == 0) ? &quot;UTF-8&quot; : &quot;UTF-16&quot;; // Get the Text Encoding
int languageCodeLength = payload[0] &amp; 0063; // Get the Language Code, e.g. &quot;en&quot;
// String languageCode = new String(payload, 1, languageCodeLength, &quot;US-ASCII&quot;);
try {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e(&quot;UnsupportedEncoding&quot;, e.toString());
}
tvNFCContent.setText(&quot;NFC Content: &quot; + 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&lt;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(),&quot;Ndefdiscovered&quot;,Toast.LENGTH_SHORT).show();
}else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
{
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(getApplicationContext(),&quot;Smartcard detected&quot;,Toast.LENGTH_SHORT).show();
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
NdefMessage[] messages = getNdefMessage(intent);            
if(messages == null)
{
Toast.makeText(getApplicationContext(),&quot;There Is No Data&quot;,Toast.LENGTH_SHORT).show();
return;
}           
byte[] payload = messages[0].getRecords()[0].getPayload();          
userData = new String(payload);
} else { 
Toast.makeText(getApplicationContext(),&quot;Undefined smartcard&quot;,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(&quot;&quot; + Minutes + &quot;:&quot;
+ String.format(&quot;%02d&quot;, Seconds) + &quot;:&quot;
+ String.format(&quot;%03d&quot;, 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
}
};
}

I'm sorry I upload the whole code, I just want to make it easy fpr anyone that would like to help me.

答案1

得分: 1

Add this code in onNewIntent()

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

Use the following method to get hex value

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();
}
英文:

Add this code in onNewIntent()

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

Use the following method to get hex value

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

答案2

得分: 0

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 = "";
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
        int languageCodeLength = payload[0] & 0063;

        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
    protected void onNewIntent(Intent intent) {
        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())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            long startTime = 0;
            long endTime = 0;

            try {
                Ndef ndefTag = Ndef.get(tag);
                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));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onResume() {
        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_DISCOVER

<details>
<summary>英文:</summary>

Finally I can make it. Thanks for everyone that helped me. Here is the full code I share it with you.


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&lt;String&gt; ListElementsArrayList ;
ArrayAdapter&lt;String&gt; 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, &quot;This device doesn&#39;t support NFC.&quot;, 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 &lt; rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}                               
buildTagViews(msgs);
}

}

private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = &quot;&quot;;

// 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(&quot;UnsupportedEncoding&quot;, e.toString());
}
tvNFCContent.setText(&quot;NFC Content: &quot; + 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&lt;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(),&quot;Smartcard detected&quot;,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(),&quot;There Is No Data&quot;,Toast.LENGTH_SHORT).show();
return;
}			
byte[] payload = messages[0].getRecords()[0].getPayload();			
userData = new String(payload);
}else
{
Toast.makeText(getApplicationContext(),&quot;Undefined smartcard&quot;,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 &quot;read&quot; 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(&quot;NFC&quot;, e.toString());
}
MillisecondTime = endTime - startTime;
UpdateTime = MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
Timer.setText(&quot;&quot; + Minutes + &quot;:&quot;
+ String.format(&quot;%02d&quot;, Seconds) + &quot;.&quot;
+ String.format(&quot;%03d&quot;, MilliSeconds));
//Log.v(&quot;NFC&quot;, &quot;Time to read in milliseconds is: &quot; + (endTime - startTime));
//Timer.setText(&quot;00:00:0.0&quot;+(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(&quot;*/*&quot;);
} 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 = &quot;0123456789abcdef&quot;.toCharArray();
for (int j = 0; j &lt; bytes.length; j++) {
int v = bytes[j] &amp; 0xFF;
hexChars[j * 2] = hexArray[v &gt;&gt;&gt; 4];
hexChars[j * 2 + 1] = hexArray[v &amp; 0x0F];
}
return new String(hexChars);
}
private long getDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i &lt; bytes.length; ++i) {
long value = bytes[i] &amp; 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private String ByteArrayToHexString(byte [] inarray) {
Log.d(&quot;ByteArrayToHexString&quot;, inarray.toString());
int i, j, in;
String [] hex = {&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;};
String out= &quot;&quot;;
for(j = 0 ; j &lt; inarray.length ; ++j)
{
in = (int) inarray[j] &amp; 0xff;
i = (in &gt;&gt; 4) &amp; 0x0f;
out += hex[i];
i = in &amp; 0x0f;
out += hex[i];
}
Log.d(&quot;ByteArrayToHexString&quot;, String.format(&quot;%0&quot; + (inarray.length * 2) + &quot;X&quot;, new BigInteger(1,inarray)));
return out;
}

}


</details>

huangapple
  • 本文由 发表于 2020年5月29日 20:20:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/62085853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定