1 the introduction
NFC stands for Near Field Communication. NFC technology is an emerging technology. Devices using NFC technology (such as mobile phones) can exchange data when they are close to each other (generally less than 10cm). It is evolved from the integration of contactless radio frequency identification (RFID) and interconnection technology. By integrating the functions of inductive card reader, inductive card and point-to-point communication on a single chip, mobile terminals are used to realize mobile payment, electronic ticketing, access control, mobile identity identification, anti-counterfeiting and other applications.
2 NFC technology
2.1 Working Mode
According to different business modes, NFC can be divided into three modes.
(1) Card reader mode
Data in the NFC chip, can be simply understood as “brush label”. It is essentially reading and writing information from labels, stickers, business cards and other media with NFC chips via NFC enabled mobile phones or other electronic devices. Generally, NFC labels do not require external power supply. When a peripheral that supports NFC reads or writes data to the NFC, it sends a magnetic field that automatically powers the NFC tag.
(2) Simulation card mode
Data in mobile phones or other electronic devices that support NFC can be simply understood as “swiping the phone”. In essence, the mobile phone or other electronic devices that support NFC are used as debit cards, bus cards, access control cards and other IC cards. The basic principle is to encapsulate the information credentials in the corresponding IC card into data packets and store them in the peripheral that supports NFC. An NFC radio frequency device (equivalent to a card reader) is also required in use. The mobile phone will be near the NFC radio frequency device, the mobile phone will receive the NFC radio frequency signal, through a series of complex verification, the corresponding information of the IC card into the NFC radio frequency device, and finally the IC card data will be passed into the NFC radio frequency connected computer, and the corresponding processing (such as electronic transfer, open the door and other operations).
(3) Point-to-point mode
This mode, similar to Bluetooth and infrared, is used for data exchange between different NFC devices, but without the “brush” feel. The effective distance generally can not exceed 4 cm, but the transmission speed is much faster than infrared and bluetooth technology, the transmission speed is much faster than infrared block, such as both sides using Android4.2, NFC will directly use bluetooth transmission. The technology is called Android Beam. So the two devices that can use Android Beam to transmit data are no longer limited to within 4cm.
A typical application for peer-to-peer mode is when two NFC-enabled phones or tablets transfer data point-to-point, for example, exchanging pictures or syncing device contacts. Therefore, through NFC, multiple devices such as digital cameras, computers, and mobile phones can quickly connect and exchange data or services.
2.2 Important Parameters
- Effective transmission range <=10cm
- There are three kinds of transmission speed: 106kbps; 212 KBPS. 424 KBPS
- Setting up a connection takes less than 1s
- NFC operates at a frequency of 13.65 MHZ
3 Development Process
3.1 Adding NFC Rights
First, declare NFC and add permissions in AndroidManifests. XML.
<uses-feature android:name="android.hardware.nfc"
android:required="true" />
<uses-permission android:name="android.permission.NFC" />
Copy the code
3.2 Adding an NFC Label
When an Android device detects an NFC Tag, it automatically looks for the most appropriate Activity to handle the Tag. Add an Intent-Filter tag to the Activity. When an NFC device is detected, the system will open the Activity. Configure the launchMode property of the Activity to singleTop and add type support information.
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/filter_nfc"></meta-data>
</activity>
Copy the code
Filter_nfc. XML file
<? The XML version = "1.0" encoding = "utf-8"? > < resources XMLNS: it = "urn: oasis: names: tc: it: document: 1.2" > < tech - list > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- A group <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 - list > < tech - list > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - group B <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>Copy the code
3.3 Initializing an Adapter
NFC development requires the NfcAdapter object provided by the Android system to manage NFC devices.
/ / get NfcAdapter object, this method is similar to obtain bluetooth adapter object mNfcAdapter = NfcAdapter. GetDefaultAdapter (getApplicationContext ()); If (mNfcAdapter == null) {toast.maketext (this, "this device does not support NFC ", toast.length_short).show(); finish(); return; } if (! mNfcAdapter.isEnabled()) { startActivity(new Intent("android.settings.NFC_SETTINGS")); Toast.maketext (this, "device not enabled NFC ", toast.length_short).show(); }Copy the code
3.4 Enabling NFC Foreground Scheduling
Turn on foreground scheduling in the Activity’s onResume method.
@Override protected void onResume() { super.onResume(); // Once the NFC message is intercepted, Through PendingIntent call window PendingIntent PendingIntent = PendingIntent. GetActivity (this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter[] intentFilters = new IntentFilter[]{}; // To enable foreground scheduling (which has the highest privileges), when the Activity is in the foreground (foreground process), Can call this method open at the front desk scheduling mNfcAdapter. EnableForegroundDispatch (this pendingIntent, intentFilters, null); }Copy the code
3.5 Receiving Data
When the mobile terminal detects that it has received NFC device data, it can receive the data in the onNewIntent method. Get the data in the Intent object as an onNewIntent method parameter.
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String ID = ByteArrayToHexString(tag.getid ()); String[] tagTechList = tag.getTechList(); if (tagTechList ! = null) { for (int i = 0; i < tagTechList.length; i++) { stringBuilder.append("*").append(tagTechList[i]).append("*").append("\n"); stringBuilder.append(readTech(tag, tagTechList[i],intent)); } } Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawArray ! = null) {// Get NDEF description NdefMessage mNdefMsg = (NdefMessage) rawArray[0]; NdefRecord mNdefRecord = mNdefMsg. GetRecords ()[0]; if (mNdefRecord ! = null) { String readResult = new String(mNdefRecord.getPayload(), "UTF-8"); }}}}Copy the code
3.6 Sending Data
Public static void writeNFCToTag(String data,) public static void writeNFCToTag(String data,) Intent intent) throws IOException, FormatException {/ / get the Tag object Tag Tag = intent. GetParcelableExtra (NfcAdapter. EXTRA_TAG); Ndef ndef = Ndef.get(tag); / / connect ndef. The connect (); NdefRecord ndefRecord = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { ndefRecord = NdefRecord.createTextRecord(null, data); } // NdefRecord[] records = {NdefRecord}; NdefMessage ndefMessage = new NdefMessage(records); // Send data ndef.writeNdefMessage(ndefMessage); }Copy the code
3.7 Disabling NFC Foreground Scheduling
NFC foreground scheduling is enabled in the Activity’s onResume method. Accordingly, NFC foreground scheduling is disabled in the onPuse method.
/ / call disableForegroundDispatch method close scheduling at the front desk if (mNfcAdapter! = null){ mNfcAdapter.disableForegroundDispatch(this); }Copy the code
4 summarizes
As an emerging technology, NFC technology has been widely concerned in the world, especially the wide application of mobile phones, which provides a premise for the rapid development of NFC technology. The principle of NFC technology is simple, so the cost is relatively low. In addition, the characteristics of high bandwidth and low energy consumption of NFC communication are also a major advantage to promote the development of NFC technology.
Public account: Programmer Meow (focus on Android study notes, interview questions and IT information sharing)