Read/write in Ndef format in android nfc

Source: Internet
Author: User

Process in Activity after detecting tags

1. Obtain the NfcAdapter object in onCreate;

NfcAdapter nfcAdapter = NfcAdapter. getdefaadapter adapter (this );

2. Obtain the Tag object or NdefMessage information in onNewIntent;

Get Tag object:

Tag tag = intent. getParcelableExra (NfcAdapter. EXTRA_TAG );

Obtain NdefMessage:

Parcelable [] rawMsgs = getIntent (). getParcelableArrayExtra (NfcAdapter. EXTRA_NDEF_MESSAGES)

3. You can also create Ndef objects using tags to implement Tag attributes and I/O operations.

Ndef ndef = Ndef. get (tag );


NDEF format label reading process

1. Obtain the NfcAdapter object in onCreate;

2. In onNewIntent (), determine whether the tag is in the NDEF format (ACTION_NDEF_DISCOVERED). If yes, obtain the NdefMessage

Information; (forced conversion to NdefMessage object)

Parcelable [] rawMsgs = getIntent (). getParcelableArrayExtra (NfcAdapter. EXTRA_NDEF_MESSAGES)

3. parse the NdefMessage object to obtain the relevant text information or Uri.


NDEF format label Writing Process

1. Obtain the NfcAdapter object in onCreate;

2. Get the Tag object in onNewIntent;

Tag tag = intent. getParcelableExra (NfcAdapter. EXTRA_TAG );

3. Create an Ndef object using tags;

Ndef ndef = Ndef. get (tag );

4. encapsulate text and other data into NdefMessage;

5. Determine whether the tag is in NDEF format,

If the format is NDEF:

(1) Allow tag operations: ndef. connect ();

(2) Call ndef. writeNdefMessage (NdefMessage) to write data.

If the format is not NDEF:

(1) NdefFromatable format = NdefFromatable. get ();

(2) allow tag operations: format. connect ();

(3) Call format. format (NdefMessage) to write data.


NdefMessage Structure



NdefRecZ records? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> cipher + c1_vcd4kpha + MS6/cipher + c1_vcd4kpha + PGJyPgo8L3A + cipher + PGJyPgo8L3A + cipher + zcrHyrW8yrXEyv2 + 3aOsxuTW0E5ERUbOxLG + JiMyNjY4NDvKvc6qo7o8YnI + ch7vcd4kpha + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140430/20140430090648250.png" alt = "\">


NDEF Uri format

1. paylaod in NdefMessage is the actual data. The NDEF text format is:


2. The prefix must be parsed using the lookup table.



Example program:

ReadWriteTextMainActivity:

Package mobile. android. read. write. text; import java. nio. charset. charset; import java. util. locale; import android. app. activity; import android. content. intent; import android. nfc. ndefMessage; import android. nfc. ndefRecord; import android. nfc. nfcAdapter; import android. nfc. tag; import android. nfc. tech. ndef; import android. nfc. tech. ndefFormatable; import android. OS. bundle; import android. view. view; import android. w Idget. textView; import android. widget. toast; public class ReadWriteTextMainActivity extends Activity {private TextView mInputText; private String mText; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_read_write_text_main); mInputText = (TextView) findViewById (R. id. textview_input_text);} // click the public vo method executed by the "Enter Text to write" button. Id onClick_InputText (View view) {Intent intent = new Intent (this, InputTextActivity. class); // startActivityForResult (intent, 1);} @ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {if (requestCode = 1 & resultCode = 1) {// obtain the text mText = data to write tags. getStringExtra ("text"); // The mInputText to be written to the tag is displayed on the main interface. setText (mText) ;}}// when the window creation mode is singleTop or single Task call, used to replace the onCreate method // when the NFC tag is near the mobile phone, call @ Override public void onNewIntent (Intent intent) after the connection is established {// if the text to be written is not set, if (mText = null) {Intent myIntent = new Intent (this, ShowNFCTagContentActivity. class); // pass intent to another window to display the interface window myIntent. putExtras (intent); // you need to specify this Action. When an Intent object is passed, the Action will not pass myIntent. setAction (NfcAdapter. ACTION_NDEF_DISCOVERED); startActivity (myIntent);} // write the specified text to the NFC tag e Lse {// get Tag OBJECT Tag = intent. getParcelableExtra (NfcAdapter. EXTRA_TAG); // create NdefMessage object and NdefRecord object NdefMessage ndefMessage = new NdefMessage (new NdefRecord [] {createTextRecord (mText )}); // start to write text to the label if (writeTag (ndefMessage, tag) {// if the text is successfully written, set mtext to null mText = null; // clear the text to be written in the main window. The text can only be written once. // to continue writing, specify the new text again. Otherwise, only the text mInputText in the label will be read. setText ("") ;}}// create an NdefRecord object publ that encapsulates the text to be written Ic NdefRecord createTextRecord (String text) {// a byte array generated for language encoding. The byte is encoded in Chinese [] langBytes = Locale. CHINA. getLanguage (). getBytes (Charset. forName ("US-ASCII"); // encode the text to be written in UTF_8 format Charset utfEncoding = Charset. forName ("UTF-8"); // Since the format of the determined text is encoded as UTF_8, the 1st bits of the payload 7th bytes are directly set to 0 byte [] textBytes = text. getBytes (utfEncoding); int utfBit = 0; // define and initialize the status byte char status = (char) (utfBit + langBytes. length); // create a storage Byte [] data = new byte [1 + langBytes. length + textBytes. length]; // sets the status byte data [0] = (byte) status; // sets the language encoding System. arraycopy (langBytes, 0, data, 1, langBytes. length); // set the actual text to be written to System. arraycopy (textBytes, 0, data, 1 + langBytes. length, textBytes. length); // create the NdefRecord object NdefRecord record = new NdefRecord (NdefRecord. TNF_WELL_KNOWN, NdefRecord. RTD_TEXT, new byte [0], d Ata); return record;} // write the NdefMessage object to a Tag. If the tag is successfully written, true is returned. Otherwise, false boolean writeTag (NdefMessage message, Tag tag) {int size = message is returned. toByteArray (). length; try {// obtain Ndef object Ndef ndef = Ndef. get (tag); if (ndef! = Null) {// allow I/O operations on tags ndef. connect (); if (! Ndef. isWritable () {Toast. makeText (this, "NFC Tag is read-only! ", Toast. LENGTH_LONG). show (); return false;} if (ndef. getMaxSize () <size) {Toast. makeText (this," NFC Tag space is insufficient! ", Toast. LENGTH_LONG). show (); return false;} // write data to the tag ndef. writeNdefMessage (message); Toast. makeText (this," data has been written successfully! ", Toast. LENGTH_LONG ). show (); return true;} else {// get the NdefFormatable object NdefFormatable that can format and write data to tags. format = NdefFormatable. get (tag); // write NDEF data if (format! = Null) {try {// allow I/O operations on tags format. connect (); format. format (message); Toast. makeText (this, "data has been written successfully! ", Toast. LENGTH_LONG). show (); return true;} catch (Exception e) {Toast. makeText (this," failed to write data in NDEF format! ", Toast. LENGTH_LONG). show (); return false ;}} else {Toast. makeText (this," NFC tags do not support NDEF format! ", Toast. LENGTH_LONG ). show (); return false ;}} catch (Exception e) {Toast. makeText (this, e. getMessage (), Toast. LENGTH_LONG ). show (); return false ;}}}

InputTextActivity:

package mobile.android.read.write.text;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.EditText;public class InputTextActivity extends Activity {    private EditText mTextTag;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_input_text);        mTextTag = (EditText) findViewById(R.id.edittext_text_tag);    }    public void onClick_OK(View view) {        Intent intent = new Intent();        intent.putExtra("text", mTextTag.getText().toString());        setResult(1, intent);        finish();    }}

ShowNFCTagContentActivity:

Package mobile. android. read. write. text; import mobile. android. read. write. text. library. textRecord; import android. app. activity; import android. content. intent; import android. nfc. ndefMessage; import android. nfc. ndefRecord; import android. nfc. nfcAdapter; import android. nfc. tag; import android. nfc. tech. ndef; import android. OS. bundle; import android. OS. parcelable; import android. widget. textView; import android. widg Et. toast; public class ShowNFCTagContentActivity extends Activity {private TextView mTagContent; private Tag mDetectedTag; private String mTagText; private void readAndShowData (Intent intent) {mDetectedTag = intent. getParcelableExtra (NfcAdapter. EXTRA_TAG); Ndef ndef = Ndef. get (mDetectedTag); mTagText = ndef. getType () + "\ n maximum data capacity:" + ndef. getMaxSize () + "bytes \ n"; readNFCTag (); mTagContent. setT Ext (mTagText) ;}@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_show_nfctag_content); mTagContent = (TextView) findViewById (R. id. textview_tag_content); // obtain the Tag object mDetectedTag = getIntent (). getParcelableExtra (NfcAdapter. EXTRA_TAG); // create Ndef object Ndef ndef = Ndef. get (mDetectedTag); // obtain the tag type and maximum capacity mTagText = ndef. getType () + "\ N maximum data capacity:" + ndef. getMaxSize () + "bytes \ n"; // read NFC tag data and parse readNFCTag (); // display tag-related information on the mTagContent page. setText (mTagText);} private void readNFCTag () {// determine whether it is ACTION_NDEF_DISCOVERED if (NfcAdapter. ACTION_NDEF_DISCOVERED.equals (getIntent (). getAction () {// read data from tags (Parcelable object) Parcelable [] rawMsgs = getIntent (). getParcelableArrayExtra (NfcAdapter. EXTRA_NDEF_MESSAGES); NdefMessage msgs [] = Null; int contentSize = 0; if (rawMsgs! = Null) {msgs = new NdefMessage [rawMsgs. length]; // The tag may store multiple NdefMessage objects. Generally, there is only one NdefMessage object for (int I = 0; I <rawMsgs. length; I ++) {// converts it to the NdefMessage object msgs [I] = (NdefMessage) rawMsgs [I]; // calculate the total length of the Data contentSize + = msgs [I]. toByteArray (). length ;}} try {if (msgs! = Null) {// only one NdefRecord object is taken into account in the program. For general purpose software, all NdefRecord objects NdefRecord record = msgs [0] should be considered. getRecords () [0]; // analyze 1st NdefRecorder and create the TextRecord object TextRecord textRecord = TextRecord. parse (msgs [0]. getRecords () [0]); // obtain the actual data usage and display mTagText + = textRecord in the window. getText () + "\ n plain text \ n" + contentSize + "bytes" ;}} catch (Exception e) {mTagContent. setText (e. getMessage ());}}}}

TextRecord:

Package mobile. android. read. write. text. library; import java. io. unsupportedEncodingException; import java. util. arrays; import android. nfc. ndefRecord; public class TextRecord {// stores the parsed text private final String mText; // The TextRecord object cannot be created directly, so the constructor is declared as private TextRecord (String text) {mText = text;} // This method can be used to obtain the parsed public String getText () {return mText;} // extract plain text content from the NdefRecord object (payload) parsing pu Blic static TextRecord parse (NdefRecord record) {// verify whether the TNF is NdefRecord. TNF_WELL_KNOWN if (record. getTnf ()! = NdefRecord. TNF_WELL_KNOWN) return null; // verify whether the variable length type is RTD_TEXT if (! Arrays. equals (record. getType (), NdefRecord. RTD_TEXT) return null; try {// get payload byte [] payload = record. getPayload (); // the following code analyzes payload: Status byte + ISO language encoding (ASCLL) + text data (UTF_8/UTF_16) // The payload [0] placement status byte: if bit7 is 0, text data is encoded in UTF_8 format. If it is 1, it is reserved in UTF_16 encoding // bit6, the default value is 0/** payload [0] contains the "Status Byte Encodings" field, per the * NFC Forum "Text Record Type Definition" section 3.2.1. ** bit7 is the Text E Ncoding Field. ** if (Bit_7 = 0): The text is encoded in UTF-8 if (Bit_7 = 1 ): * The text is encoded in UTF16 ** Bit_6 is reserved for future use and must be set to zero. ** Bits 5 to 0 are the length of the IANA language code. */String textEncoding = (payload [0] & 0x80) = 0 )? "UTF-8": "UTF-16"; // processing bit5-0. Bit5-0 represents the language encoding length (bytes) int bytes agecodelength = payload [0] & 0x3f; // gets the language encoding (reads languageCodeLength bytes from the 2nd bytes of payload as the language encoding) string languageCode = new String (payload, 1, languageCodeLength, "US-ASCII"); // parse the actual text data String text = new String (payload, languageCodeLength + 1, payload. length-shortagecodelength-1, textEncoding); // create a TextRecord object and return the return new TextRecord (text);} catch (UnsupportedEncodingException e) {// shocould never happen unless we get a malformed tag. throw new IllegalArgumentException (e );}}}


AndroidManifest. xml:
      
       
                           
                                   
                
               
                                   
                    
                
                               
  


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.