Reputation: 608
we want to write the following data into NFC:(In two separate lines)
Id:A112
Result:Pass
and got stuck with NdefRecord
creation of MIME type text/plain. Actually found two ways of doing so:
one with constuctor
public NdefRecord (short tnf, byte[] type, byte[] id, byte[] payload)
other one by using the Static method
public static NdefRecord createMime (String mimeType, byte[] mimeData)
Using the static createMime
method, we can create the record as:
byte[] stringBytes = "Id:A112Result:Pass".getBytes();
NdefRecord.createMime("text/plain", stringBytes);
How to achieve the same with constructor NdefRecord
and what's the difference between the above two ways? Also how do we write the above data (Id:A112Result:Pass) into NFC in two lines into a single record.
Upvotes: 0
Views: 1761
Reputation: 40849
The equivalent of
public static NdefRecord createMime (String mimeType, byte[] mimeData)
using the NdefRecord
constructor directly is something like this:
public NdefRecord myCreateMime (String mimeType, byte[] mimeData) {
return new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
mimeType.getBytes("US-ASCII"),
null,
mimeData)
}
In general I would avoid using the text/plain MIME type. This MIME type does not give the payload data any meaning other than it is human-readable text. If you want to convey a specific meaning use an appropriate MIME type that reflects the contents of your payload data or better use a custom NFC Forum external type.
Also note that the MIME type text/plain uses US-ASCII character encoding by default. However, using "Id:A112Result:Pass".getBytes()
will give you UTF-8 encoding on Android. So you should explicitly specify the character encoding when converting a string to bytes:
byte[] stringBytes = "Id:A112Result:Pass".getBytes("US-ASCII");
Last, if you want to insert a line break anywhere in a text, you would use the new-line escape character \n
or a combination of carriage return + line feed \r\n
(depending on your target system's needs).
Upvotes: 1