Java Reference
In-Depth Information
NDEF defines
messages
consisting of one or more
records,
each in a lightweight
binary message format that consists of a payload type, optional payload identifier, and
payload itself. For example, to read any pending NDEF records, you might write the code
shown in Listing 15-9.
Listing 15-9.
Reading Pending NDEF Records
public static void readMessage()
{
try
{
NDEFMessage message = conn.readNDEF();
if(message == null)
{
return;
}
NDEFRecord[] records = message.getRecords();
if(records == null)
{
return;
}
System.out.println("Got "+records.length+" records.");
for (int i = 0; i < records.length; i++)
{
NDEFRecordType type = records[i].getRecordType();
System.out.println("id: " + new String(records[i].getId()) );
System.out.println("type: " + type.getName() );
System.out.println("payload: " + new String(records[i].getPayload()));
}
} catch (Exception e) { … }
}
This code walks the list of returned records, printing the ID and payload of each
message. Messages may also bear a type, available by invoking the record's
getRecordType
function, which returns an instance of
NDEFRecordType
. This type defines several record
types, including
EMPTY
,
NFC_FORUM_RTD
,
MIME
,
URI
,
EXTERNAL_RTD
, and
UNKNOWN
. A common
type is the URI type, which indicates that the payload of the message is a URL, such as
one offered by a Smart Poster device.
If you need to write records to the NDEF target, you can create a new
NDEFRecord
and
use the
NDEFTagConnection
's
writeNDEF
method. When you define a new
NDEFRecord
,you
must supply the record's type, ID, and payload, as shown in Listing 15-10.