Read and write in ndef format in Android NFC

Source: Internet
Author: User

Process flow in activity after a label is detected

1. Obtain the Nfcadapter object in OnCreate ();

Nfcadapter Nfcadapter = Nfcadapter.getdefaultadapter (this);

2. Obtain the Tag object or ndefmessage information in onnewintent ();

Get the Tag object:

Tag tag = Intent.getparcelableexra (Nfcadapter.extra_tag);

Get ndefmessage Information:

parcelable[] Rawmsgs = Getintent (). Getparcelablearrayextra (Nfcadapter.extra_ndef_messages)

3. You can also create Ndef objects by tag to achieve the properties and I/O operations of the tags.

Ndef Ndef = ndef.get (tag);


Read flow for ndef format labels

1. Obtain the Nfcadapter object in OnCreate ();

2. In Onnewintent () to determine whether the NDEF format label (action_ndef_discovered), if you get Ndefmessage

(Need to cast to Ndefmessage object)

parcelable[] Rawmsgs = Getintent (). Getparcelablearrayextra (Nfcadapter.extra_ndef_messages)

3. Parse the Ndefmessage object to get the relevant text information or URI, etc.


NDEF format Label Writing process

1. Obtain the Nfcadapter object in OnCreate ();

2. Obtain the Tag object in Onnewintent ();

Tag tag = Intent.getparcelableexra (Nfcadapter.extra_tag);

3. Create Ndef object through tag;

Ndef Ndef = ndef.get (tag);

4. Encapsulate the text and other data into ndefmessage;

5. Determine if the NDEF format label is

If Ndef format:

(1) Allow label operation: Ndef.connect ();

(2) Call the Ndef.writendefmessage (Ndefmessage) method to write.

Unless Ndef format:

(1) ndeffromatable format = Ndeffromatable.get ();

(2) Allow label operation: Format.connect ();

(3) Call the Format.format (Ndefmessage) method to write.


Ndefmessage Information Structure



The common methods in Ndefrecord

1. The TNF field can be obtained through the NDEFRECORD.GETTNF () method;

2. Use the Ndefrecord.gettype () method to obtain the RTD field when the TNF is tnf_well_known.

3. Use the Ndefrecord.getpayload () method to obtain the actual read and write data.



Ndef Text Format

The paylaod in Ndefmessage is the actual data, where the Ndef text format is:



NDEF URI Format

1, Ndefmessage in the paylaod is the actual data, wherein the NDEF text format is:


2, the prefix needs to check the table parsing



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.widget.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 "Enter text to write" button to perform the method public void Onclick_inputtext (view view) {Intent Intent = new Intent (This, inputtexta        Ctivity.class); Display the input text interface Startactivityforresult (intent, 1); } @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode =            = 1 && ResultCode = = 1) {//Gets the text to be written to the label MText = Data.getstringextra ("text");        Displays the text to be written to the label in the main interface Minputtext.settext (MText); }}//When the window's creation mode is Singletop or singletask, it is used to replace the OnCreate method//When the NFC tag is close to the phone, the connection is called @Override public void Onnewinten T (Intent Intent) {//If the text to be written is not set, the text data on the label is read if (MText = = null) {Intent myintent = new Intent (th            is, Shownfctagcontentactivity.class);            Pass intent to another window, display the interface window Myintent.putextras (intent);            This action needs to be specified, and when the intent object is passed, the action does not pass myintent.setaction (nfcadapter.action_ndef_discovered);        StartActivity (myintent); }//writes the specified text to the NFC tag else {//Get tag Object tag tag = Intent.getparcelableextra (nfcadapter.extr            A_tag);    Creating Ndefmessage objects and Ndefrecord objects        Ndefmessage ndefmessage = new Ndefmessage (new ndefrecord[] {Createtextrecord (MText)}); Start writing to label text if (Writetag (ndefmessage, tag)) {//If the text is successfully written, MText is set to null MText                = NULL;            The text to be written to the main window is emptied, the text can only be written once//to continue writing, the new text needs to be specified again, or only the text Minputtext.settext ("") in the label will be read; }}}//Create a Ndefrecord object that encapsulates the text to be written public Ndefrecord Createtextrecord (String text) {//Generate language-encoded bytes        Array, Chinese code byte[] langbytes = Locale.CHINA.getLanguage (). GetBytes (Charset.forname ("Us-ascii"));        The text that will be written is encoded in utf_8 format Charset utfencoding = Charset.forname ("UTF-8");        Since the format encoding of the text has been determined to be utf_8, the 7th bit of the 1th byte of payload is set directly to 0 byte[] textbytes = text.getbytes (utfencoding);        int utfbit = 0;        Defines and initializes the status byte char status = (char) (utfbit + langbytes.length); Create a byte array that stores payload byte[] data = new Byte[1 + Langbytes.length + TexTbytes.length];        Set status byte data[0] = (byte) status;        Set language encoding system.arraycopy (langbytes, 0, data, 1, langbytes.length);        Set the actual text to be written system.arraycopy (textbytes, 0, data, 1 + langbytes.length, textbytes.length); Create Ndefrecord objects based on the payload set above Ndefrecord record = new Ndefrecord (Ndefrecord.tnf_well_known, Ndefrec Ord.        Rtd_text, new byte[0], data);    return record; }//Writes Ndefmessage object to label, successfully writes return ture, otherwise returns false Boolean Writetag (Ndefmessage message, tag tag) {int size = Messa        Ge.tobytearray (). length;            try {//Get Ndef object Ndef Ndef = ndef.get (tag);                if (ndef! = null) {//Allow IO operation on label 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 does not have enough space!                    ", Toast.length_long). Show ();                return false;                }//Write Data ndef.writendefmessage (message) to tag; Toast.maketext (This, "the data has been successfully written!                ", Toast.length_long). Show ();            return true;                } else {//Gets the Ndefformatable object that can format and write data to the label ndefformatable format = ndefformatable.get (tag);                        Writes NDEF format data to a non-ndef or unformatted label if (format! = null) {try {                        Allow IO operation on the label Format.connect ();                        Format.format (message); Toast.maketext (This, "the data has been successfully written!                        ", Toast.length_long). Show ();                    return true; } catch (Exception e) {Toast.maketext (this, "write Ndef format data failed!         ", Toast.length_long)                       . Show ();                    return false; }} else {Toast.maketext (this, "NFC tag does 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.widget.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\n";        Readnfctag ();    Mtagcontent.settext (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);        Gets the TAG object mdetectedtag = Getintent (). Getparcelableextra (Nfcadapter.extra_tag);        Create Ndef object Ndef Ndef = Ndef.get (Mdetectedtag);        Gets the type of label and maximum capacity Mtagtext = Ndef.gettype () + "\ n Maximum data capacity:" + ndef.getmaxsize () + "bytes\n\n";        Read the NFC tag data and parse the Readnfctag ();    The relevant information of the label is displayed on the interface Mtagcontent.settext (Mtagtext); } private void Readnfctag () {//To determine if action_ndef_discovered if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals ( Getintent (). Getaction ()) {//Read data from tag (Parcelable object) parcelable[] rawmsgs = Getintent (). getparcelable            Arrayextra (nfcadapter.extra_ndef_messages);            Ndefmessage msgs[] = null;            int contentsize = 0;                if (rawmsgs! = null) {msgs = new ndefmessage[rawmsgs.length]; //tag may store multiple Ndefmessage objects, typically only one Ndefmessage object for (int i = 0; i < rawmsgs.length; i++) {                    Convert to Ndefmessage object Msgs[i] = (ndefmessage) rawmsgs[i];                Calculates the total length of the data contentsize + = Msgs[i].tobytearray (). length; }} try {if (msgs! = null) {//The program only considers 1 Ndefrecord objects, if the generic software should consider all                    The Ndefrecord object Ndefrecord record = Msgs[0].getrecords () [0];                            Analyze 1th Ndefrecorder and create Textrecord object Textrecord Textrecord = Textrecord.parse (Msgs[0]                    . GetRecords () [0]); Gets the actual data occupied by the size and displayed on the window Mtagtext + = Textrecord.gettext () + "\ n \ nthe plain text \ n" + cont                Entsize + "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 {//store parsed text private final String MText;    The Textrecord object is not allowed to be created directly, so the construction method is declared as private private Textrecord (String text) {mText = text;    }//Through this method you can get the parsed text public String GetText () {return mText; }//resolves plain text content from the Ndefrecord object (payload) public static Textrecord parse (Ndefrecord record) {//Verify that TNF is Ndefrec Ord.        Tnf_well_known if (RECORD.GETTNF ()! = Ndefrecord.tnf_well_known) return null; Verify that 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: State byte +iso language encoding (ASCLL) + Text data (UTF_8/UTF_16)//where payload[0] placement state byte: If BIT7 is 0, text data is encoded in UTF_8 format, if 1 is utf_1 6 encoding//bit6 is reserved bit, default is 0/* * Payload[0] contains the "Status Byte encodings" field, per the * NFC Forum "Text Record Type D             Efinition "section 3.2.1.             * * BIT7 is the Text Encoding 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 the future use and must are set to zero.             * * Bits 5 to 0 is the length of the IANA language code. */String textencoding = ((payload[0] & 0x80) = = 0)?            "UTF-8": "UTF-16"; Handle bit5-0.            bit5-0 indicates language encoding length (bytes) int languagecodelength = payload[0] & 0x3f; Gets the language encoding (read Languagecodelength bytes from the 2nd byte of payload as the language encoding) string languagecode = new String (payload, 1, Languagecode            Length, "Us-ascii"); Parse out the actual text data string text = new String (payload, Languagecodelength + 1, Payload.length-languagecodelength-1, textencoding);        Creates a Textrecord object and returns the object return new Textrecord (text);            } catch (Unsupportedencodingexception e) {//should never happen unless we get a malformed tag.        throw new IllegalArgumentException (e); }    }}


Androidmanifest.xml:
<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Mobile.android.read.write.text" Android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "android"        : targetsdkversion= "/> <uses-permission android:name=" Android.permission.NFC "/> <application        android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= ".            Readwritetextmainactivity "android:label=" read-write NFC tag plain text data "android:launchmode=" Singletask "> <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <ca Tegory android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> <intent-filte r> <action android:name= "Android.nfc.action.NDEF_DISCOVERED"/> &Lt;category android:name= "Android.intent.category.DEFAULT"/> <data android:mimetype= "Text/plain"/&G            T </intent-filter> </activity> <activity android:name= ". Shownfctagcontentactivity "android:label=" displays the NFC tag content "android:launchmode=" Singletask "/> &L T;activity android:name= ". Inputtextactivity "android:label=" to the NFC tag write text "/> </application></manifest>


Related Article

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.