通过Android NFC传输纯文本,可以通过以下步骤实现:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
<uses-permission android:name="android.permission.NFC" />
NdefMessage ndefMessage = new NdefMessage(
new NdefRecord[] { NdefRecord.createTextRecord(null, "Hello, NFC!") });
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);
@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标签,并将纯文本数据写入标签中。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云