Realization of Android to Read the Number of NFC Card

  • 2021-12-19 06:57:50
  • OfStack

In this paper, we share the specific code of Android reading NFC card number for your reference, the specific contents are as follows

NFC Related androidManifest File Settings:

1. Permission: < uses-permission android:name="android.permission.NFC"/ >
2. sdk level limit: < uses-sdk android:minSdkVersion="10"/ >
3. Special functional limitations < uses-feature android:name="android.hardware.nfc" android:required="true" / > This life allows your application to be declared on google play that users must have nfc functionality.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfc"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-permission android:name="android.permission.NFC" />
 
    <uses-feature
        android:name="android.hardware.nfc"
        android:required="true" />
 
    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.nfc.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
            <intent-filter>
                <action android:name="android.nfc.action.TECH_DISCOVERED" />
            </intent-filter>
 
            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/nfc_tech_filter" />
 
        </activity>
    </application>
 
</manifest>

The above android: resource= "@ xml/nfc_tech_filter" is a filter condition for tech type. Create a new xml folder and a new nfc_tech_filter. xml file in res folder.


<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.IsoDep</tech>
        <tech>android.nfc.tech.NfcA</tech>        
        <tech>android.nfc.tech.NfcB</tech>
        <tech>android.nfc.tech.NfcF</tech>
        <tech>android.nfc.tech.NfcV</tech>
        <tech>android.nfc.tech.Ndef</tech>
        <tech>android.nfc.tech.NdefFormatable</tech>
        <tech>android.nfc.tech.MifareClassic</tech>
        <tech>android.nfc.tech.MifareUltralight</tech>
    </tech-list>
</resources>

The following is a class that encapsulates the reading NFC card number:


class NFCCard {
 
 private Activity context;
 private PendingIntent pendingIntent;
 private NfcAdapter adapter;
 private IntentFilter[] intentFilters;
 private String[][] techLists;
 private final char[] HEX_EXCHANGE = { '0', '1', '2', '3', '4', '5', '6',
   '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
 
 public NFCCard(Context context) {
  this.context = (Activity) context;
 }
 
 void init() {
 
  adapter = NfcAdapter.getDefaultAdapter(context);
  //  Create 1 A PendingIntent Object, when the Android When the system scans to the label, it will populate this object. 
  pendingIntent = PendingIntent.getActivity(context, 0, new Intent(
    context, context.getClass())
    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
  IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
  try {
   ndef.addDataType("*/*");
  } catch (MalformedMimeTypeException e) {
   throw new RuntimeException("fail", e);
  }
  intentFilters = new IntentFilter[] { ndef, };
  techLists = new String[][] { new String[] { MifareClassic.class
    .getName() } };
 }
 
 public boolean open() {
  // TODO  Open NfcAdapter If it is already open, return true . Should be in onResume() Call in 
  if (adapter != null)
   adapter.enableForegroundDispatch(context, pendingIntent,
     intentFilters, techLists);
  return adapter.isEnabled();
 }
 
 public boolean close() {
  // TODO  Shut down NfcAdapter If it is closed, return true
  if (adapter != null)
   adapter.disableForegroundDispatch(context);
  return !adapter.isEnabled();
 }
 
 public String getId(Intent intent) {
  // TODO Get NFC Card number. Should be in onNewIntent() Call in 
  Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  return toHexString(tagFromIntent.getId(), 0,
    tagFromIntent.getId().length);
 }
 
 private String toHexString(byte[] d, int s, int n) {
  // TODO  Convert to 106 String in binary form 
  final char[] ret = new char[n * 2];
  final int e = s + n;
  int x = 0;
  for (int i = s; i < e; ++i) {
   final byte v = d[i];
   ret[x++] = HEX_EXCHANGE[0x0F & (v >> 4)];
   ret[x++] = HEX_EXCHANGE[0x0F & v];
  }
  return new String(ret);
 }

It should be noted that there is one "android: launchMode =" singleTask "in the above configuration file, which sets the application as a single task. getId (Intent intent) in the code must be executed in onNewIntent (Intent intent) of Activity. Because when the system detects the NFC card, it will automatically generate Intent encapsulated with the corresponding Tag. When the application receives Intent, it starts its own Activity by default, which will cause a new Activity to start every time it receives Intent. After setting the application as a single task, this situation can be avoided.


Related articles: