android nfc guide
httpsww//:w.theitroad.com
Near Field Communication (NFC) is a technology that allows two devices to exchange data wirelessly over a short distance. Android provides a set of APIs that allow developers to build apps that use NFC technology. Here's a brief guide to help you get started with Android NFC development:
- Check device compatibility: Not all Android devices have NFC hardware, so the first step is to check whether the device supports NFC. You can use the
PackageManager
to check for theNFC
feature. Here's an example code:
PackageManager pm = getPackageManager(); if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) { // NFC is not supported }
- Enable NFC in your app: To use NFC in your app, you need to declare the
NFC
permission in your app's manifest file:
<uses-permission android:name="android.permission.NFC" />
- Handle NFC intents: Android apps can receive NFC intents when a device is tapped with an NFC tag. You can handle these intents in your app's activity or service by overriding the
onNewIntent()
method. Here's an example code:
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { // Handle the NFC intent } }
- Write to NFC tags: You can use the
NdefRecord
class to create a data record to write to an NFC tag. Here's an example code:
NdefRecord record = NdefRecord.createUri("http://www.example.com"); NdefMessage message = new NdefMessage(new NdefRecord[] { record }); NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); nfcAdapter.setNdefPushMessage(message, this);
- Read from NFC tags: You can use the
Ndef
class to read data from an NFC tag. Here's an example code:
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { NdefMessage[] messages = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { messages[i] = (NdefMessage) rawMsgs[i]; } NdefRecord record = messages[0].getRecords()[0]; String data = record.toUri().toString(); }
These are just some examples of the NFC APIs available in Android. Depending on your app's specific needs, you may need to use additional APIs or third-party libraries to build a complete NFC solution.