1 向BPS请求NFC事件;
2 把你的应用注册到tag发现事件;
nfc_result_t rc = nfc_register_tag_readerwriter(TAG_TYPE_NDEF);
if
(rc != NFC_RESULT_SUCCESS) {
// Handle error
...
}
4检查和提取NDEF信息
void
handle_event(bps_event_t event) {
...
int
rc;
unsigned
int
ndefMsgCount = 0;
nfc_event_t* nfcEvent = NULL;
nfc_target_t* target = NULL;
if
(NFC_TAG_READWRITE_EVENT == bps_event_get_code(event)) {
rc = nfc_get_nfc_event(event, &nfcEvent);
// get target
nfc_get_target(nfcEvent, &target);
nfc_get_ndef_message_count(target, &ndefMsgCount);
// loop through and parse NDEF messages
for
(
int
ndefMsgIndex = 0; ndefMsgIndex < ndefMsgCount;
++ndefMsgCount) {
nfc_ndef_message_t *ndefMessage;
nfc_get_ndef_message(target, ndefMsgIndex,
&ndefMessage);
// parse NDEF message
parseNdefMessage(ndefMessage);
// free resources
nfc_destroy_target(target);
}
}
}
void
parseNdefMessage(nfc_ndef_message_t *ndefMessage) {
int
ndefMsgCount = 0;
ndefMsgCount = 1;
unsigned
int
ndefRecordCount = 0;
nfc_get_ndef_record_count(ndefMessage, &ndefRecordCount);
for
(unsigned
int
ndefRecordIndex = 0;
ndefRecordIndex < ndefRecordCount;
++ndefRecordIndex) {
// For each NDEF record, use NFC API functions to
// retrieve data. Below we retrieve:
// the NDEF record,
// the payload,
// the record Type Name Format (TNF),
// the record type, and
// the record ID.
nfc_ndef_record_t *ndefRecord;
nfc_get_ndef_record(ndefMessage, ndefRecordIndex,
&ndefRecord);
uchar_t* ndefRecordPayloadData;
size_t
ndefRecordPayloadLength;
nfc_get_ndef_record_payload(ndefRecord,
&ndefRecordPayloadData,
&ndefRecordPayloadLength);
tnf_type_t ndefRecordTnf;
nfc_get_ndef_record_tnf(ndefRecord, &ndefRecordTnf);
char
*ndefRecordNdefType;
nfc_get_ndef_record_type(ndefRecord,
&ndefRecordNdefType);
char
*ndefRecordIdentifier;
nfc_get_ndef_record_id(ndefRecord,
&ndefRecordIdentifier);
...
// Determine what type of record we have received.
// If record type is "Smart Poster"
if
(
strcmp
(ndefRecordNdefType,
Settings::NfcRtdSmartPoster) == 0) {
// Do what you need to with the data;
// e.g., record it in a log
...
char
*utf_title;
char
*found_lang;
char
*uri;
nfc_ndef_rtd_encoding_t rtd_encoding;
rtd_encoding = UTF_8;
// Obtain the smart poster title and URI
nfc_get_sp_title(ndefRecord,
"en"
, &utf_title,
&found_lang, &rtd_encoding,
true
);
nfc_get_sp_uri(ndefRecord, &uri);
// Do what you need to with the data;
// e.g., write to a log
...
// Free resources
free
(utf_title);
free
(uri);
}
else
if
(
strcmp
(ndefRecordNdefType,
Settings::NfcRtdUri) == 0) {
// If record type is "URI"
...
}
else
if
(
strcmp
(ndefRecordNdefType,
Settings::NfcRtdText) == 0) {
// If record type is "Text"
...
}
}