我得到了这个代码,当应用程序打开时它可以正常工作。我希望即使应用程序关闭也能够传输数据,或者至少在您将 NFC 标签靠近手机时显示打开应用程序的警报。我正在使用react-native-nfc-manager。
我的目标是让它在 Android 和 iOS 上都能运行,但暂时只在 Android 上运行就好了。
import React, { useEffect, useState } from 'react';
import {
Text,
SafeAreaView,
View,
TouchableOpacity,
StyleSheet
} from 'react-native';
import NfcManager, { NfcEvents } from 'react-native-nfc-manager';
const App = () => {
const [hasNfc, setHasNFC] = useState(null);
useEffect(() => {
const checkIsSupported = async () => {
const deviceIsSupported = await NfcManager.isSupported()
setHasNFC(deviceIsSupported)
if (deviceIsSupported) {
await NfcManager.start()
}
}
checkIsSupported()
}, [])
useEffect(() => {
readTag()
NfcManager.setEventListener(NfcEvents.DiscoverTag, (tag) => {
console.log('tag found', tag)
console.log(tag.ndefMessage[0].payload.toString('utf8'))
if (tag.ndefMessage && tag.ndefMessage.length > 0) {
// Iterate through the NDEF records
for (let i = 0; i < tag.ndefMessage.length; i++) {
const record = tag.ndefMessage[i];
console.log(record)
// Check the record's type (TNF) and payload
if (record.tnf === 1) { // TNF 1 corresponds to well-known types (e.g., text or URI)
// Assuming the payload is text data, you can decode it
const payloadText = String.fromCharCode.apply(null, record.payload);
console.log(`NDEF Record ${i + 1}: ${payloadText}`);
}
}
}
})
return () => {
NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
}
}, [])
const readTag = async () => {
await NfcManager.registerTagEvent();
}
if (hasNfc === null) return null;
if (!hasNfc) {
return (
<View style={styles.sectionContainer}>
<Text>NFC not supported</Text>
</View>
)
}
return (
<SafeAreaView style={styles.sectionContainer}>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
sectionContainer: {
backgroundColor: 'white',
flex: 1,
alignItems: 'center'
},
})
export default App;
当您的应用程序关闭时,您无法从 NFC 读取数据(因为显然您的应用程序未运行),有两种不同的方法来配置特定的 NFC 标签以在前台启动您的应用程序(一种用于 iOS,一种用于 Android)。
一旦您的应用程序由正确配置的 NFC 标签启动,您就可以读取它。