How to Read Nfc Tags on Lg Stylo

android reading writing nfc tags

Android Reading and Writing NFC Tags

NFC (Near Field Advice) is a communication protocol which allows two devices to communicate and transfer information within a short distance. Some of the midrange to high-end Android devices has NFC support which allows you lot to utilize the feature.

NFC Tags are small chips which yous can arrive the form of stickers, cards, rings or even keychain. They can store a small amount of data in the range of hundreds of bytes. These are passive things which can piece of work without a power supply or rely on other devices for ability such as an NFC Tag depends on your Phone or the NFC readers to piece of work.

Here I accept bought a set of 5 tags for iv$ (₹250) from Amazon. The NFC tags I have can store data up to 144 bytes. There are unlike types of NFC tags which can shop a larger amount of data.

android reading and writing nfc tags

-> Read and Write a small amount of data such as URL, Contact information, etc.

-> Tin can be used to launch apps.

-> Can exist used to unlock your device.

-> Security keys for App.

These are some of the applications. NFC Tags can have endless possibilities.

In this tutorial, we are going to brand an app which can read and write text to an NFC tag.

Brand certain your device supports NFC. You can confirm this by Settings -> More -> NFC

android reading and writing nfc tags

Purchase NFC Tags to test with our App. You can get NFC Tags from online retailers such as Amazon.

Hither I accept created an Android Studio project with packet com.learn2crack.nfc besides Activity as MainActivity and layout as activity_main.

Adding Permissions to Manifest

We need to add the NFC permission to Manifest to employ the NFC capability.

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

Since we are using Java viii Lambda functions, we demand to enable Jack compiler and set compileOptions to Java version eight. Insert the snippet similar to the one defined below.

              apply plugin: 'com.android.application'  android {     compileSdkVersion 25     buildToolsVersion "25.0.0"     defaultConfig {         applicationId "com.learn2crack.nfc"         minSdkVersion 19         targetSdkVersion 25         versionCode one         versionName "one.0"         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"          jackOptions {             enabled truthful         }     }      compileOptions {         sourceCompatibility JavaVersion.VERSION_1_8         targetCompatibility JavaVersion.VERSION_1_8     }      buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     }  }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     androidTestCompile('com.android.support.test.espresso:espresso-core:ii.2.2', {         exclude group: 'com.android.support', module: 'back up-annotations'     })     compile 'com.android.support:appcompat-v7:25.0.0'     testCompile 'junit:junit:iv.12' }            

Defining String constants

Instead of hard coding we define strings in res-> values-> strings.xml and refer information technology from this file whenever needed.

              <resources>     <cord proper name="app_name">NFC</string>     <cord name="message_write_error">Error Writing Bulletin !</cord>     <cord name="message_write_success">Successfully written to Tag !</cord>     <cord proper name="message_write_progress">Writing to Tag..</cord>     <string name="message_tag_detected">NFC Tag Detected !</cord>     <string name="message_read_tag">Read from NFC Tag</cord>     <cord proper name="message_write_tag">Write to NFC Tag</string>     <string name="message_tap_tag">Tap the NFC Tag to your device !</string>     <string name="hint_message">Bulletin</string> </resources>            

Our chief activity layout has an input EditText widget and two Buttons.

              <?xml version="1.0" encoding="utf-eight"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/activity_main"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:gravity="center"     tools:context="com.learn2crack.nfc.MainActivity">      <EditText         android:id="@+id/et_message"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:hint="@string/hint_message"/>      <Push         android:id="@+id/btn_write"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_below="@+id/et_message"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:text="@string/message_write_tag"         way="@style/Widget.AppCompat.Button.Colored"/>      <Push button         android:id="@+id/btn_read"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_below="@+id/btn_write"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:text="@string/message_read_tag"         style="@fashion/Widget.AppCompat.Button.Colored"/> </RelativeLayout>            

The side by side layout is for write dialog which is a DialogFragment. It has two TextViews and an ImageView widget.

              <?xml version="ane.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="@dimen/activity_horizontal_margin">      <TextView         android:id="@+id/championship"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="centre"         android:text="@cord/message_write_tag"         android:textAppearance="?android:attr/textAppearanceLarge"/>      <ImageView         android:id="@+id/logo"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:src="@drawable/ic_nfc"         android:tint="@color/colorAccent"/>      <ProgressBar         android:id="@+id/progress"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="eye"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:visibility="gone"/>      <TextView         android:id="@+id/tv_message"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="heart"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:text="@cord/message_tap_tag"/>  </LinearLayout>            

The side by side layout is for read dialog which displays the contents of the NFC tag.

              <?xml version="1.0" encoding="utf-viii"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="@dimen/activity_horizontal_margin">      <TextView         android:id="@+id/championship"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="@cord/message_read_tag"         android:textAppearance="?android:attr/textAppearanceLarge"         android:layout_gravity="center"/>      <ImageView         android:id="@+id/logo"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:src="@drawable/ic_nfc"         android:tint="@color/colorAccent"         android:layout_gravity="center"/>      <TextView         android:id="@+id/tv_message"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="@dimen/activity_horizontal_margin"         android:layout_gravity="centre"         android:textAppearance="?android:attr/textAppearanceMedium"/>  </LinearLayout>            

Creating Listener interface

We create a listener interface which implements two methods onDialogDisplayed() and onDialogDismissed().

              parcel com.learn2crack.nfc;  public interface Listener {      void onDialogDisplayed();      void onDialogDismissed(); }            

Hither we override two Fragment lifecycle methods onAttach() and onDetach(). Our MainActivity implements the interface nosotros created before. We call the listener'south onDialogDisplayed() method in onAttach() and then that the MainActivity can be notified when the dialog is displayed. Similarly, onDialogDismissed() is called in onDetach() and so that the MainActivity knows when the dialog is dismissed.

We define the writeToNfc() method to write data to the NFC tag. In NFCs data is written in a standardized format called NDEF (NFC Data Commutation Format). Android has inbuilt support to create and write NDEF messages. Here nosotros are going to write a manifestly text message to NFC tag. And then we use the MIME type text/plain. Then we create a new NdefRecord object with MIME blazon and text we want to write in the tag. Then we write the data using the writeNdefMessage() method.

              package com.learn2crack.nfc;  import android.app.DialogFragment; import android.content.Context; import android.nfc.FormatException; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.tech.Ndef; import android.bone.Package; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView;  import coffee.io.IOException; import java.nio.charset.Charset;  public class NFCWriteFragment extends DialogFragment {      public static final String TAG = NFCWriteFragment.class.getSimpleName();      public static NFCWriteFragment newInstance() {          return new NFCWriteFragment();     }      private TextView mTvMessage;     individual ProgressBar mProgress;     private Listener mListener;      @Nullable     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Package savedInstanceState) {         View view = inflater.inflate(R.layout.fragment_write,container,false);         initViews(view);         return view;     }      private void initViews(View view) {          mTvMessage = (TextView) view.findViewById(R.id.tv_message);         mProgress = (ProgressBar) view.findViewById(R.id.progress);     }      @Override     public void onAttach(Context context) {         super.onAttach(context);         mListener = (MainActivity)context;         mListener.onDialogDisplayed();     }      @Override     public void onDetach() {         super.onDetach();         mListener.onDialogDismissed();     }      public void onNfcDetected(Ndef ndef, String messageToWrite){          mProgress.setVisibility(View.VISIBLE);         writeToNfc(ndef,messageToWrite);     }      private void writeToNfc(Ndef ndef, String message){          mTvMessage.setText(getString(R.string.message_write_progress));         if (ndef != null) {              try {                 ndef.connect();                 NdefRecord mimeRecord = NdefRecord.createMime("text/plain", message.getBytes(Charset.forName("US-ASCII")));                 ndef.writeNdefMessage(new NdefMessage(mimeRecord));                 ndef.shut();                 //Write Successful                 mTvMessage.setText(getString(R.string.message_write_success));              } take hold of (IOException | FormatException east) {                 e.printStackTrace();                 mTvMessage.setText(getString(R.string.message_write_error));              } finally {                 mProgress.setVisibility(View.GONE);             }          }     } }            

Similarly for reading the bulletin we ascertain readFromNFC() method. We read data using getNdefMessage() method which returns NdefMessage object.

              package com.learn2crack.nfc;  import android.app.DialogFragment; import android.content.Context; import android.nfc.FormatException; import android.nfc.NdefMessage; import android.nfc.tech.Ndef; import android.bone.Packet; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;  import java.io.IOException;  public class NFCReadFragment extends DialogFragment {      public static last Cord TAG = NFCReadFragment.class.getSimpleName();      public static NFCReadFragment newInstance() {          return new NFCReadFragment();     }      private TextView mTvMessage;     individual Listener mListener;      @Nullable     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          View view = inflater.inflate(R.layout.fragment_read,container,imitation);         initViews(view);         render view;     }      private void initViews(View view) {          mTvMessage = (TextView) view.findViewById(R.id.tv_message);     }      @Override     public void onAttach(Context context) {         super.onAttach(context);         mListener = (MainActivity)context;         mListener.onDialogDisplayed();     }      @Override     public void onDetach() {         super.onDetach();         mListener.onDialogDismissed();     }      public void onNfcDetected(Ndef ndef){          readFromNFC(ndef);     }      private void readFromNFC(Ndef ndef) {          endeavor {             ndef.connect();             NdefMessage ndefMessage = ndef.getNdefMessage();             String message = new Cord(ndefMessage.getRecords()[0].getPayload());             Log.d(TAG, "readFromNFC: "+message);             mTvMessage.setText(message);             ndef.close();          } catch (IOException | FormatException e) {             eastward.printStackTrace();          }     } }            

Our MainActivity is the entry point for our application. Instead of defining Intent filters for the NFC tag in Manifest we define within out Activity and use it with enableForegroundDispatch() method. We also need to laissez passer a PendingIntent to this enableForegroundDispatch() method. Nosotros use the Intent flag as FLAG_ACTIVITY_SINGLE_TOP which makes sure if the Activity is already running information technology pass the data to our running Action instead of launching a new one. This enableForegroundDispatch() method intercepts all the NFC events and makes certain our Activeness is the first one to receive it. We use this in our Activity lifecycle onResume() method. Similarly, we disable using disableForegroundDispatch() method on Activity's onPause() method.

The Action's newIntent() method is chosen on an NFC event. Nosotros obtain the Tag object from the Intent parcelable extra. We then become a Ndef object from the Tag object and laissez passer it to the respective read or write fragment for read or write operation.

              package com.learn2crack.nfc;  import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.support.v7.app.AppCompatActivity; import android.os.Parcel; import android.util.Log; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;  public course MainActivity extends AppCompatActivity implements Listener{      public static final String TAG = MainActivity.class.getSimpleName();      private EditText mEtMessage;     private Button mBtWrite;     private Push button mBtRead;      private NFCWriteFragment mNfcWriteFragment;     private NFCReadFragment mNfcReadFragment;      private boolean isDialogDisplayed = false;     individual boolean isWrite = imitation;      private NfcAdapter mNfcAdapter;      @Override     protected void onCreate(Parcel savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          initViews();         initNFC();     }      private void initViews() {          mEtMessage = (EditText) findViewById(R.id.et_message);         mBtWrite = (Button) findViewById(R.id.btn_write);         mBtRead = (Button) findViewById(R.id.btn_read);          mBtWrite.setOnClickListener(view -> showWriteFragment());         mBtRead.setOnClickListener(view -> showReadFragment());     }      private void initNFC(){          mNfcAdapter = NfcAdapter.getDefaultAdapter(this);     }      private void showWriteFragment() {          isWrite = true;          mNfcWriteFragment = (NFCWriteFragment) getFragmentManager().findFragmentByTag(NFCWriteFragment.TAG);          if (mNfcWriteFragment == null) {              mNfcWriteFragment = NFCWriteFragment.newInstance();         }         mNfcWriteFragment.show(getFragmentManager(),NFCWriteFragment.TAG);      }      private void showReadFragment() {          mNfcReadFragment = (NFCReadFragment) getFragmentManager().findFragmentByTag(NFCReadFragment.TAG);          if (mNfcReadFragment == zip) {              mNfcReadFragment = NFCReadFragment.newInstance();         }         mNfcReadFragment.show(getFragmentManager(),NFCReadFragment.TAG);      }      @Override     public void onDialogDisplayed() {          isDialogDisplayed = truthful;     }      @Override     public void onDialogDismissed() {          isDialogDisplayed = false;         isWrite = false;     }      @Override     protected void onResume() {         super.onResume();         IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);         IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);         IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);         IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};          PendingIntent pendingIntent = PendingIntent.getActivity(                 this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);         if(mNfcAdapter!= zippo)             mNfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);      }      @Override     protected void onPause() {         super.onPause();         if(mNfcAdapter!= cipher)             mNfcAdapter.disableForegroundDispatch(this);     }      @Override     protected void onNewIntent(Intent intent) {         Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);          Log.d(TAG, "onNewIntent: "+intent.getAction());          if(tag != naught) {             Toast.makeText(this, getString(R.string.message_tag_detected), Toast.LENGTH_SHORT).testify();             Ndef ndef = Ndef.get(tag);              if (isDialogDisplayed) {                  if (isWrite) {                      Cord messageToWrite = mEtMessage.getText().toString();                     mNfcWriteFragment = (NFCWriteFragment) getFragmentManager().findFragmentByTag(NFCWriteFragment.TAG);                     mNfcWriteFragment.onNfcDetected(ndef,messageToWrite);                  } else {                      mNfcReadFragment = (NFCReadFragment)getFragmentManager().findFragmentByTag(NFCReadFragment.TAG);                     mNfcReadFragment.onNfcDetected(ndef);                 }             }         }     } }            

This program volition not work on a virtual device. Make certain yous exam it on a physical device with NFC.

You can download the complete project as zip or fork from our Github repository.


This is simply the intro tutorial. NFC has enormous potential and a ton of applications. You tin expect more tutorials on NFC from us.

Stay tuned!

Enjoy coding 🙂

soundybrothe47.blogspot.com

Source: https://www.learn2crack.com/2016/10/android-reading-and-writing-nfc-tags.html

0 Response to "How to Read Nfc Tags on Lg Stylo"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel