Reading and Using Nfc Chips in Android Studio
How to Create an NFC App for Android
NFC is a technology mostly used in cyberbanking, and oftentimes developers create NFC payment apps for business. However, there are endless ways to apply it, and you can exist really creative with it. No wonder information technology is gaining popularity amidst users and developers, equally information technology'southward present in about mod mobile devices. In this article I'll show you how to build an NFC awarding and exist a bit creative with it.
Almost Field Communication, a engineering that was announced back in 2004. It allows wireless information exchange over short distances — around ten centimeters (4 inches) or less — with a chip that's embedded in a device. This engineering was derived from RFID and allows users to connect to other devices, make payments, ship media and files, and use NFC tags, which probably is the most creative way to apply this technology. You can create an NFC scanner app for almost anything.
Though this technology appeared a long time ago, it has found its use primarily in contactless payments. Other than contactless payments, Near field communication isn't used for much else other than for enabling quick connections to Bluetooth devices. Yous can apply NFC tags and other devices to record any information.
In that location are some out-of-the-box solutions, as virtually Android device manufacturers already provide near field advice Android apps. For example, y'all can put Wi-Fi data into an NFC tag and only scan information technology instead of typing in a Wi-Fi countersign.
Withal, you can exist really artistic about the functionality and create your custom solution.
For case, I'm a dark owl, and sometimes information technology's hard for me to wake up in the morning. I just turn off the alarm and go back to sleep. I decided to have some fun with NFC tags to solve my problem. The plan was to create an alert that doesn't go off until I scan an NFC tag that'south in the kitchen.
This would inevitably brand me wake upwardly and walk to the kitchen. After that, I probably wouldn't return to my bed.
To do this, I needed to build an alarm app with an NFC tag. Well-nigh field communication technology can be used in lots of things, and in this article I want to show you how to work with unlike types of information y'all can record on a tag to plough your ideas into reality.
Let me show you how you can create an NFC scanner app step by footstep.
How to create an NFC app
Now I'll show you lot how to record different types of data to your NFC tag in practice by describing how I built my own app. Y'all'll need Android Studio and an NFC tag.
1. Creating a project
Starting time, I created a project in Android Studio.
two. Creating UI
So I wrote a simple UI for my application.
I added four types of tags to my application: plainly text, phone number, link, and location.
3. Creating the principal class
At this point I had to pay attention to the main class of my app.
To brainstorm with, I initialized the NFCManager form I created.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mNfcManager = new NFCManager(this);
}
After that, I checked if NFC was available on my device and allowed the app to receive notifications if a tag is nearby.
@Override
protected void onResume() {
super.onResume();
endeavour {
mNfcManager.verifyNFC();
Intent nfcIntent = new Intent(this, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[]{};
String[][] techList = new String[][]{{android.nfc.tech.Ndef.class.getName()}, {android.nfc.tech.NdefFormatable.form.getName()}};
NfcAdapter nfcAdpt = NfcAdapter.getDefaultAdapter(this);
nfcAdpt.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techList);
} catch (NFCManager.NFCNotSupported nfcnsup) {
Toast.makeText(this, "NFC not supported", Toast.LENGTH_SHORT).bear witness();
} grab (NFCManager.NFCNotEnabled nfcnEn) {
Toast.makeText(this, "NFC Non enable", Toast.LENGTH_SHORT).show();
}
}
Then I blocked notifications when the app is inactive.
@Override
protected void onPause() {
super.onPause();
mNfcManager.disableDispatch();
}
I installed IntentFilter and defined an onNewIntent method, which will be triggered each time the device finds an NFC tag nearby. When I got near the tag, I recorded my message on it.
@Override
public void onNewIntent(Intent intent) {
mCurrentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (mNfcMessage != null) {
mNfcManager.writeTag(mCurrentTag, mNfcMessage);
mDialog.dismiss();
Toast.makeText(this, "Tag written", Toast.LENGTH_SHORT).testify();
}
}
Depending on which RadioButton is chosen, a different message is recorded to the NFC tag.
@OnClick(R.id.btn_write)
public void onWrite() {
Cord content = mTextContent.getText().toString();
switch (mRadioGroup.getCheckedRadioButtonId()) {
case R.id.radio_text:
mNfcMessage = mNfcManager.createTextMessage(content);
break;
case R.id.radio_uri:
mNfcMessage = mNfcManager.createUriMessage(content, "https://");
interruption;
case R.id.radio_phone:
mNfcMessage = mNfcManager.createUriMessage(content, "tel:");
break;
instance R.id.radio_geo:
mNfcMessage = mNfcManager.createGeoMessage();
break;
}
if (mNfcMessage != aught) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Tag NFC Tag please");
mDialog.bear witness();
}
}
4. Making NFC piece of work
I created a class that'southward responsible for working with NFC. I called this class NFCManager and I added all the methods to information technology that you tin can run into in MainActivity.
4.1. Hither'south a method to bank check if NFC is available on a device.
public void verifyNFC() throws NFCNotSupported, NFCNotEnabled {
nfcAdpt = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdpt == nothing)
throw new NFCNotSupported();
if (!nfcAdpt.isEnabled())
throw new NFCNotEnabled();
}
iv.2. This method unsubscribes from receiving notifications.
public void disableDispatch() {
nfcAdpt.disableForegroundDispatch(activity);
}
4.iii. Hither'due south a method for recording data to an NFC tag. If necessary, you tin format the tag first and then record your data to it.
public void writeTag(Tag tag, NdefMessage bulletin) {
if (tag != null) {
attempt {
Ndef ndefTag = Ndef.get(tag);
if (ndefTag == null) {
NdefFormatable nForm = NdefFormatable.get(tag);
if (nForm != null) {
nForm.connect();
nForm.format(message);
nForm.close();
}
} else {
ndefTag.connect();
ndefTag.writeNdefMessage(message);
ndefTag.close();
}
} catch (Exception due east) {
e.printStackTrace();
}
}
}
4.four. This is a method for creating a bulletin that contains a link or a telephone number.
public NdefMessage createUriMessage(String content, String blazon) {
NdefRecord record = NdefRecord.createUri(type + content);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
return msg;
}
iv.5. Here y'all can see the method for a message that contains plain text.
public NdefMessage createTextMessage(Cord content) {
endeavor {
byte[] lang = Locale.getDefault().getLanguage().getBytes("UTF-8");
byte[] text = content.getBytes("UTF-viii"); // Content in UTF-8 int langSize = lang.length;
int textLength = text.length; ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + langSize + textLength);
payload.write((byte) (langSize & 0x1F));
payload.write(lang, 0, langSize);
payload.write(text, 0, textLength);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
return new NdefMessage(new NdefRecord[]{record});
} catch (Exception eastward) {
e.printStackTrace();
} return null;
}
four.6. This method will allow yous to create a message with location coordinates.
public NdefMessage createGeoMessage() {
Cord geoUri = "geo:" + 48.471066 + "," + 35.038664;
NdefRecord geoUriRecord = NdefRecord.createUri(geoUri);
return new NdefMessage(new NdefRecord[]{geoUriRecord});
}
4.7. At this point, you lot need to mention non-typical errors in your code that the user will see if NFC isn't available.
public static class NFCNotSupported extends Exception {
public NFCNotSupported() {
super();
}
} public static class NFCNotEnabled extends Exception {
public NFCNotEnabled() {
super();
}
} }
five. Finally, my application is ready!
Now I can launch and test it.
The commencement thing I do is insert a link and press the Write Tag button.
Then I need to become the device closer to the tag to tape the data.
To test how information technology went, I close the app and bring the device closer to the tag. The link should now open in a browser.
If I record geolocation, I get this screen:
Did everything work for you? If so, congrats! Now y'all know how to make an NFC app for Android which methods to use in order to create NFC applications for different purposes. Retail, marketing, tracking, or lifestyle applications — NFC scanner app development can aid you lot with any idea you take.
Withal, if y'all're planning to create a payment app, you demand to think about encrypting the information transfer between the tag and the device.
If you have any questions on how to develop an NFC reader app, exist sure to write to Mobindustry. Also, don't forget to rate this article — I want to know whether information technology was useful for yous.
Get a Complimentary Consultation!
sales@mobindustry.net
https://www.mobindustry.net/how-to-create-an-nfc-app-for-android/
Reading and Using Nfc Chips in Android Studio
Source: https://medium.com/@mobindustry/how-to-create-an-nfc-app-for-android-c76a40d564d
0 Response to "Reading and Using Nfc Chips in Android Studio"
Post a Comment