android Realizes NFC Read Write Function

  • 2021-12-19 07:00:52
  • OfStack

1. What is NFC?

Near field communication technology, which evolved from contactless radio frequency identification (RFID), was jointly developed by Philips Semiconductors (now NXP Semiconductors), Nokia and Sony, and is based on RFID and interconnection technology. Near field communication (Near Field Communication, NFC) is a short-range high-frequency radio technology, which operates within 20 cm at 13.56 MHz frequency. Its transmission speed is 106 Kbit/s, 212 Kbit/s or 424 Kbit/s. At present, near field communication has become the international standard of ISO/IEC IS 18092, ECMA-340 and ETSI TS 102 190. NFC adopts active and passive reading modes.

NFC communication modes mainly include the following (information sources):

1. Reader Mode (Reader/writer mode):

Use as a contactless card reader, such as reading relevant information from posters or electronic tags of exhibition information. It can also realize the data exchange between NFC mobile phones, which will bring many conveniences for file sharing in enterprise environment or multi-player game applications.

2. Point-to-point mode (P2Pmode):

This mode is similar to infrared, and can be used for data exchange, but the transmission distance is short, the transmission creation speed is fast, the transmission speed is also fast, and the power consumption is low (Bluetooth is similar). Wireless link between two devices with NFC function enables point-to-point data transmission, such as downloading music, exchanging pictures or synchronizing device address books. Therefore, through NFC, multiple devices such as digital cameras, PDA, computers and mobile phones can exchange data or services.

3. Card Mode (Cardemulation):

This model is actually equivalent to an IC card using RFID technology, which can replace a large number of occasions where IC cards (including credit cards) are used, such as shopping mall swiping cards, bus cards, access control, tickets, tickets and so on. In this way, there is a great advantage, that is, the card is powered by the RF domain of the contactless card reader, and it can work even if the host device (such as mobile phone) is dead.

2. How to use and integrate into projects?

1. First, declare NFC in manifests and add corresponding permissions;


<uses-feature  
        android:name="android.hardware.nfc"  
        android:required="true" />  
        <uses-permission android:name="android.permission.NFC" />

2. Declare and identify the NFC tag in the Activity tag;


<activity android:name=".Activity.Main.NFCActivity">  
    <intent-filter>  
        <action android:name="android.nfc.action.TAG_DISCOVERED" />  

        <category android:name="android.intent.category.DEFAULT" />  

        <data android:mimeType="*/*" />  
    </intent-filter>  
</activity>

3. Encapsulate the reading and writing of NFC, which is convenient to call;


public class NfcUtils {  

    //nfc  
    public static NfcAdapter mNfcAdapter;  
    public static IntentFilter[] mIntentFilter = null;  
    public static PendingIntent mPendingIntent = null;  
    public static String[][] mTechList = null;  

    /** 
     *  Constructor, which is used to initialize the nfc
     */  
    public NfcUtils(Activity activity) {  
        mNfcAdapter = NfcCheck(activity);  
        NfcInit(activity);  
    }  

    /** 
     *  Check NFC Whether to open  
     */  
    public static NfcAdapter NfcCheck(Activity activity) {  
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);  
        if (mNfcAdapter == null) {  
            return null;  
        } else {  
            if (!mNfcAdapter.isEnabled()) {  
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);  
                activity.startActivity(setNfc);  
            }  
        }  
        return mNfcAdapter;  
    }  

    /** 
     *  Initialization nfc Settings  
     */  
    public static void NfcInit(Activity activity) {  
        mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);  
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);  
        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);  
        try {  
            filter.addDataType("*/*");  
        } catch (IntentFilter.MalformedMimeTypeException e) {  
            e.printStackTrace();  
        }  
        mIntentFilter = new IntentFilter[]{filter, filter2};  
        mTechList = null;  
    }  

    /**  
     *  Read NFC Data of   
     */  
    public static String readNFCFromTag(Intent intent) throws UnsupportedEncodingException {  
        Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);  
        if (rawArray != null) {  
            NdefMessage mNdefMsg = (NdefMessage) rawArray[0];  
            NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];  
            if (mNdefRecord != null) {  
                String readResult = new String(mNdefRecord.getPayload(), "UTF-8");  
                return readResult;  
            }  
        }  
        return "";  
    }  


    /** 
     *  To nfc Write data  
     */  
    public static void writeNFCToTag(String data, Intent intent) throws IOException, FormatException {  
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
        Ndef ndef = Ndef.get(tag);  
        ndef.connect();  
        NdefRecord ndefRecord = NdefRecord.createTextRecord(null, data);  
        NdefRecord[] records = {ndefRecord};  
        NdefMessage ndefMessage = new NdefMessage(records);  
        ndef.writeNdefMessage(ndefMessage);  
    }  

    /** 
     *  Read nfcID 
     */  
    public static String readNFCId(Intent intent) throws UnsupportedEncodingException {  
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
        String id = ByteArrayToHexString(tag.getId());  
        return id;  
    }  

    /** 
     *  Convert a byte array to a string  
     */  
    private static String ByteArrayToHexString(byte[] inarray) {  
        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];  
        }  
        return out;  
    }  
} 

4. The use of NFCActivity code, the foreground dispatching system using tags;


@Override  
public void initData() {  
    //nfc Initialization settings   
    NfcUtils nfcUtils = new NfcUtils(this);  
} 

@Override  
protected void onResume() {  
    super.onResume();  
    // Start the foreground dispatching system   
    NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);  
}

@Override  
protected void onPause() {  
    super.onPause();  
    // Shut down the foreground dispatching system   
    NfcUtils.mNfcAdapter.disableForegroundDispatch(this);  
}

@Override  
protected void onNewIntent(Intent intent) {  
    super.onNewIntent(intent);  
    // When the Activity Received NFC Tag, run the method   
    // Call the tool method to read NFC Data   
    String str = NfcUtils.rendFromTag(intent);  
}

Related articles: