Using NFC in Android application development

Using NFC in Android application development

Introduction to NFC

NFC stands for Near Field Communication, which is a short-range wireless communication technology that allows devices to communicate without contact or at a very short distance. NFC is commonly used in mobile payments, access control systems, smart tags and other IoT applications.

The Android system provides extensive support for NFC. Through NFC technology, Android devices can communicate with other NFC devices, read information on NFC tags, and perform NFC payment and other operations.

To use the NFC function in an Android application, you need to declare the corresponding permissions and features in the AndroidManifest.xml file and use NFC-related APIs in the application code. At the same time, you also need to ensure that the device supports the NFC function and the user has turned on the NFC function.

 // 检查设备是否支持NFC NfcManager nfcManager = (NfcManager) getSystemService(Context.NFC_SERVICE); NfcAdapter nfcAdapter = nfcManager.getDefaultAdapter(); if (nfcAdapter != null && nfcAdapter.isEnabled()) { // NFC可用,执行相应的操作} else { // NFC不可用,给出相应的提示}

In actual applications, you can use NFC-related Intent filters to respond to operations such as reading and writing NFC tags, or you can use NFC-related APIs for more flexible operations.

The Android system provides good support for NFC, and developers can make full use of this feature to add more interactivity and convenience to their applications.

NFC Usage

How to use NFC to read card information on Android. First, make sure your device supports NFC.

(1) Add the necessary permissions to the AndroidManifest.xml file:

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

(2) Register NFC-related intent filters in your Activity:

 <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" />

(3) Create an NFC reading callback function and initialize the NFC adapter in the onCreate method:

 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); // 检查设备是否支持NFC,并且NFC是否已经开启if (nfcAdapter != null && nfcAdapter.isEnabled()) { // 在onCreate方法中注册NFC事件处理器IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); IntentFilter[] filters = new IntentFilter[]{tagDetected}; // 创建一个PendingIntent对象,以便系统可以在检测到NFC标签时通知你的应用PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); // 在onResume方法中启用前台调度nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, null); }

(4) Process the NFC tag read event and read information from the tag:

 @Override protected void onNewIntent(Intent intent) { if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // 从标签中读取信息} }

(5) Create a nfc_tech_filter.xml file in the AndroidManifest.xml file to specify the NFC tag type you want to process:

 <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-list> </resources>

With the above steps, you can use NFC to read card information in your Android application.

Example of using the NFC writer class to write text information to an NFC card:

 // 创建一个NFC写入器类public class NFCWriter { private NfcAdapter nfcAdapter; private PendingIntent pendingIntent; private IntentFilter[] intentFilters; private String[][] techLists; public NFCWriter(Activity activity) { nfcAdapter = NfcAdapter.getDefaultAdapter(activity); Intent intent = new Intent(activity, activity.getClass()); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0); IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndef.addDataType("*/*"); } catch (IntentFilter.MalformedMimeTypeException e) { throw new RuntimeException("fail", e); } intentFilters = new IntentFilter[]{ndef}; techLists = new String[][]{new String[]{NfcF.class.getName()}}; } // 写入NDEF消息到NFC卡片public void writeNdefMessage(Tag tag, NdefMessage message) { try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); ndef.writeNdefMessage(message); ndef.close(); } else { NdefFormatable formatable = NdefFormatable.get(tag); if (formatable != null) { formatable.connect(); formatable.format(message); formatable.close(); } } } catch (Exception e) { e.printStackTrace(); } } }

Summarize

NFC (Near Field Communication) is a wireless technology used for data transmission and communication within a short distance. On Android devices, NFC can be used to implement a variety of functions, such as payment, data transmission, access control cards, etc.

(1) Hardware support: Make sure that the device supports NFC and the user has enabled the NFC function.

(2) Permission declaration: Declare NFC permissions in the AndroidManifest.xml file.

 <uses-permission android:name="android.permission.NFC" />

(3) Detect NFC function: Detect in the application whether the device supports the NFC function and whether it has been turned on.

(4) Create NFC interaction: Create NFC interaction related operations, such as reading NFC tags, writing NFC tags, and processing NFC data.

(5) Handle NFC intent: Register NFC intent filters so that the application can respond with appropriate actions when an NFC tag is detected.

 <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="application/*" /> </intent-filter>

(6) Processing NFC data: When the application receives an NFC intent, it processes the data in the NFC tag and performs corresponding operations.

NFC development involves hardware support, permission declaration, NFC function detection, NFC interaction creation, NFC intent processing, etc. Through reasonable processing, rich NFC functions can be realized to provide users with a more convenient experience.

<<:  Things about Android application hardening

>>:  How much do you know about mobile biometric authentication?

Recommend

How can APP accurately discover users’ real needs?

Regarding user needs, there is a very famous case...

How to attract new users through APP user operations?

How will we leverage the momentum, coordinate res...

What is the use of the “blue” in Isatis root?

As a common household medicine for clearing away ...

What is ketosis? Eating meat makes you thinner?

Audit expert: Shen Yingjian Director of the Nutri...

Where is the future of new media operations?

A few months ago, a friend who works in new media...

What licenses do e-commerce websites need?

The past 10 years have been the golden age of e-c...

The logic behind traffic: How to achieve community fission growth?

This article uses real data to deeply reveal the ...

B station's "soft core" marketing

2020 is the year when Bilibili’s marketing began ...