The above footage from our NFC Workshop walks Android developers through code which demonstrates how to read content and parse messages from an NFC tag.

You can follow along below or download the source here.

(Note: It may be beneficial to first read the previous post on writing content to an NFC tag which prefaces material in this post.)





We start by setting up an intent filter and grabbing our default adapter.


We create a pending intent and apply the 'FLAG_ACTIVITY_SINGLE_TOP' method to ensure that we don't create multiple instances of the same application.


The intent filter is going to look a little different than it did when we were writing to a tag.  Here, we add the scheme (http), the data authority (www.smartwhere.com), and the path (.*).  

We're being explicit about what we want to receive, giving us higher priority in the dispatch model. 


 public class MainActivity extends Activity {  
      private static final String TAG = "NFCReadTag";  
      private NfcAdapter mNfcAdapter;  
      private IntentFilter[] mNdefExchangeFilters;  
      private PendingIntent mNfcPendingIntent;  
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
           mNfcAdapter = NfcAdapter.getDefaultAdapter(this);  
        mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,  
                     getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP  
                     | Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);  
           IntentFilter smartwhere = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);  
           smartwhere.addDataScheme("http");  
           smartwhere.addDataAuthority("www.smartwhere.com", null);  
           smartwhere.addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);  
           mNdefExchangeFilters = new IntentFilter[] { smartwhere };  
   }  



At onResume() we check to see if the NFC adapter is enabled and we execute enableForegroundDispatch(), passing in our pending intent and filters. 


   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     getMenuInflater().inflate(R.menu.activity_main, menu);  
     return true;  
   }  
      @Override  
      protected void onResume() {  
           super.onResume();  
           if(mNfcAdapter != null) {  
                mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,  
                     mNdefExchangeFilters, null);  
                if (!mNfcAdapter.isEnabled()){  
            LayoutInflater inflater = getLayoutInflater();  
               View dialoglayout = inflater.inflate(R.layout.nfc_settings_layout,(ViewGroup) findViewById(R.id.nfc_settings_layout));  
            new AlertDialog.Builder(this).setView(dialoglayout)  
                   .setPositiveButton("Update Settings", new DialogInterface.OnClickListener() {  
                        public void onClick(DialogInterface arg0, int arg1) {  
                                      Intent setnfc = new Intent(Settings.ACTION_WIRELESS_SETTINGS);  
                                      startActivity(setnfc);  
                        }  
                   })  
                .setOnCancelListener(new DialogInterface.OnCancelListener() {  
                     public void onCancel(DialogInterface dialog) {  
                          finish(); // exit application if user cancels  
                  }                      
                }).create().show();  
                }  
           } else {  
                Toast.makeText(getApplicationContext(), "Sorry, No NFC Adapter found.", Toast.LENGTH_SHORT).show();  
           }  
      }  

At 'onPause()' we execute disableForegroundDispatch().


'onNewIntent()' is where we get the intent once we've tapped the tag.  Then we can use 'getParceableExtra()' to get the tag data and build an NDEF message array.


In this example, we are just looking for the first message and the first record, grabbing its payload, and displaying it.



      @Override  
      protected void onPause() {  
           super.onPause();  
           if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);  
      }  
      @Override  
      protected void onNewIntent(Intent intent) {  
           super.onNewIntent(intent);            
           if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {  
                NdefMessage[] messages = null;  
                Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);  
                if (rawMsgs != null) {  
                     messages = new NdefMessage[rawMsgs.length];  
                     for (int i = 0; i < rawMsgs.length; i++) {  
                          messages[i] = (NdefMessage) rawMsgs[i];  
                     }  
                }  
                if(messages[0] != null) {  
                     String result="";  
                     byte[] payload = messages[0].getRecords()[0].getPayload();  
                     // this assumes that we get back am SOH followed by host/code  
                     for (int b = 1; b<payload.length; b++) { // skip SOH  
                          result += (char) payload[b];  
                     }  
                     Toast.makeText(getApplicationContext(), "Tag Contains " + result, Toast.LENGTH_SHORT).show();  
                }  
           }  
      }  
 }  

Video: NFC Workshop, July 17, 2012
Location: Seattle Waterfront
Post by: Kelsey W



6

View comments

  1. Can you please post the source for the layout also?

    ReplyDelete
    Replies
    1. As this code was constructed for a demo, there isn't much of a layout. However, you can go to the following path to see all of the source: http://www.tapwise.com/svn/nfcreadtag/trunk/

      Delete
    2. it's can't read tag?
      because?

      Delete

(The "Imagine That" series highlights benefits & conveniences of NFC by looking at differences in every day encounters with and without the technology)

You're walking through the mall with your girlfriend—Lululemon bags in hand from the two grueling hours of shopping you’ve just completed—when, completely unexpectedly, a Dark Knight Rises poster catches your eye.  You have been waiting for this moment for months.  Is there any possible way that Christopher Nolan has outdone himself yet again?  You don’t know—but you’d like to find out.  That’s when it hits you: your newly Lulu-outfitted girlfriend might not go for it.
1

One of the biggest advantages of NFC over other technologies is that it's handled by the operating system.  This means that you don't have to download an application to read NFC tags or worry about whether or not your application functions with the type of tag you are trying to read.

The above footage from our NFC Workshop walks Android developers through code which demonstrates how to read content and parse messages from an NFC tag.

You can follow along below or download the source here.

(Note: It may be beneficial to first read the previous post on writing content to an NFC tag which prefaces material in this post.)

We start by setting up an intent filter and grabbing our default adapter.
6

The above footage from our NFC Workshop walks Android developers through code which demonstrates how to write content to an NFC tag. 

You can follow along below or download the source here. 

We start by coming into our 'onCreate()' and getting the default NFC adapter.

We want to create our pending intent as a 'FLAG_ACTIVITY_SINGLE_TOP' so that as we tap it, we aren't creating multiple instances of the same application.
7

Last week, we held an NFC workshop for the Seattle developer community in association with SEADroid, providing a high-level overview of NFC fundamentals and a hands-on introduction to incorporating NFC functionality into mobile applications. 

In short, it was a great success (admittedly, I was a little disappointed that only three of the over 60 attendees were women--see for yourself above).  We had a good-sized turnout and an awesome crowd of Android-savvy developers.

Isn't it annoying when you go down the street to your favorite coffee shop to get some work done and you end up spending a major chunk of time just getting set up?  You came here to get work done, not spend twenty minutes trying to connect to the WiFi.  It's bad enough that you've already had to wait around for a table to open up--we've all been there--the last thing you need is another time-suck.
1
Labels
Blog Archive
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.