首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何通过Android NFC传输纯文本?

通过Android NFC传输纯文本,可以通过以下步骤实现:

  1. 确保设备支持NFC功能,并且已经打开了NFC开关。
  2. 在Android应用中,首先需要获取NFC适配器对象,可以使用以下代码获取:
代码语言:txt
复制
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
  1. 确保应用已经获得了NFC权限,在AndroidManifest.xml文件中添加以下权限:
代码语言:txt
复制
<uses-permission android:name="android.permission.NFC" />
  1. 创建一个NDEF消息,用于存储要传输的纯文本数据。可以使用以下代码创建一个包含纯文本的NDEF消息:
代码语言:txt
复制
NdefMessage ndefMessage = new NdefMessage(
    new NdefRecord[] { NdefRecord.createTextRecord(null, "Hello, NFC!") });
  1. 在应用中注册一个NDEF消息的写入回调函数,用于在检测到NFC标签时写入NDEF消息。可以使用以下代码注册回调函数:
代码语言:txt
复制
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndefIntentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
    ndefIntentFilter.addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
    e.printStackTrace();
}
IntentFilter[] intentFiltersArray = new IntentFilter[] { ndefIntentFilter };
String[][] techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
  1. 在Activity的onNewIntent方法中处理NDEF消息的写入操作,可以使用以下代码将NDEF消息写入NFC标签:
代码语言:txt
复制
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            try {
                ndef.connect();
                ndef.writeNdefMessage(ndefMessage);
                ndef.close();
                Toast.makeText(this, "NFC传输成功!", Toast.LENGTH_SHORT).show();
            } catch (IOException | FormatException e) {
                e.printStackTrace();
            }
        }
    }
}

以上步骤完成后,当设备靠近支持NFC的标签时,应用将自动检测到NFC标签,并将纯文本数据写入标签中。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云移动推送:https://cloud.tencent.com/product/tpns
  • 腾讯云物联网通信平台:https://cloud.tencent.com/product/iotexplorer
  • 腾讯云数据库 MySQL 版:https://cloud.tencent.com/product/cdb-for-mysql
  • 腾讯云区块链服务:https://cloud.tencent.com/product/tbaas
  • 腾讯云云原生容器服务:https://cloud.tencent.com/product/tke
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

47秒

工程监测多通道振弦模拟信号采集仪VTN如何OEM定制呢

49秒

工程监测多通道振弦模拟信号采集仪VTN如何OEM代工

3分59秒

基于深度强化学习的机器人在多行人环境中的避障实验

45秒

工程监测多通道振弦传感器无线采发仪该如何选择

领券