Qt NFC 概述

With the Qt NFC API typical use cases are:

  • Detecting NFC tags.
  • Reading and writing NDEF messages.
  • Registering NDEF message handlers.
  • Sharing files and messages.

The following sections describe how to use Qt NFC C++ classes and QML types for the above use cases.

注意: On Android, the detection of new NFC tags only works in foreground applications. Android services do not support this because of API limitations on the Android side. The only way to use a Tag in a service is to provide an AIDL interface accepting the Tag and forward it to Qt as shown in the following example.

public void setTag(Tag pTag) {
    Intent newIntent = new Intent();
    newIntent.putExtra(NfcAdapter.EXTRA_TAG, pTag);
    QtNative.onNewIntent(newIntent);
}
					

C++ 概述

The C++ API provides access to the full feature set of the Qt NFC API. This section introduces the major features available to developers.

检测 NFC 标签

QNearFieldManager class is responsible for the detection of new NFC tags coming into range of the device. The QNearFieldManager::targetDetected () 和 QNearFieldManager::targetLost () signals are emitted when a tag comes into or leaves the range. The passed QNearFieldTarget parameter acts as primary interaction point for each detected tag. The detection does not actually start though until QNearFieldManager::startTargetDetection () 被调用。

m_manager = new QNearFieldManager(this);
connect(m_manager, &QNearFieldManager::targetDetected,
        this, &MainWindow::targetDetected);
connect(m_manager, &QNearFieldManager::targetLost,
        this, &MainWindow::targetLost);
m_manager->startTargetDetection(QNearFieldTarget::NdefAccess);
					

Finally the detection can be stopped:

m_manager->stopTargetDetection();
					

Although each QNearFieldTarget instance is owned by its related QNearFieldManager instance it can be beneficial to manually delete each instance. Otherwise they would continue to exist until the QNearFieldManager instance is deleted. The best way to do that would be in response to the QNearFieldManager::targetLost () signal:

void MainWindow::targetLost(QNearFieldTarget *target)
{
    target->deleteLater();
}
					

注意: The target object should only be deleted via deleteLater() if it is deleted inside the slot.

连接 NFC 标签

All functions of QNearFieldTarget that require a connection will create one by its own. An active connection will prevent other instances to create a connection because only one connection at the time is allowed.

Qt 5 disconnected the tag at the end of the functions to allow other instances to connect. QNearFieldManager::setKeepConnection() allowed to change this behavior.

Since Qt 6, QNearFieldTarget keeps the connection by default. The connection is only closed when the QNearFieldTarget is destroyed or QNearFieldManager::disconnect () 被调用。

读写 NDEF (NFC 数据交换格式) 消息

QNearFieldTarget instance returned by QNearFieldManager::targetDetected () signal is used to interact with the tag. Reading and writing a message is an asynchronous operation. The QNearFieldTarget::RequestId class associates individual operations and their results.

void MainWindow::targetDetected(QNearFieldTarget *target)
{
    switch (m_touchAction) {
    case NoAction:
        break;
    case ReadNdef:
        connect(target, &QNearFieldTarget::ndefMessageRead, this, &MainWindow::ndefMessageRead);
        connect(target, &QNearFieldTarget::error, this, &MainWindow::targetError);
        m_request = target->readNdefMessages();
        if (!m_request.isValid()) // cannot read messages
            targetError(QNearFieldTarget::NdefReadError, m_request);
        break;
    case WriteNdef:
        connect(target, &QNearFieldTarget::requestCompleted, this, &MainWindow::ndefMessageWritten);
        connect(target, &QNearFieldTarget::error, this, &MainWindow::targetError);
        m_request = target->writeNdefMessages(QList<QNdefMessage>() << ndefMessage());
        if (!m_request.isValid()) // cannot write messages
            targetError(QNearFieldTarget::NdefWriteError, m_request);
        break;
    }
}
					

Once the QNearFieldTarget::readNdefMessages () request was successfully processed, the QNearFieldTarget::ndefMessageRead () signal is emitted. Each returned QNdefMessage may consist of zero or more QNdefRecord entries, which can be identified by their type. For more information about processing of records, see the QNdefRecord class documentation. As the above code demonstrates, writing of NDEF messages is triggered via QNearFieldTarget::writeNdefMessages (). The successful completion of the write operation is indicated by the emission of the QNearFieldTarget::requestCompleted () signal with the corresponding request id. Any type of error during read or write is indicated via QNearFieldTarget::error ().