React Native NFC 管理器初始化出错

问题描述 投票:0回答:1

您好,我有以下代码:

import React, { useEffect } from 'react';
import { View, Text, Button, Alert } from 'react-native';
import { NfcTech } from 'react-native-nfc-manager';
import NfcManager from 'react-native-nfc-manager';

const NFCWriterCom = () => {
  useEffect(() => {
    async function initNfc() {
      try {
        await NfcManager.start();
        console.log('NFC Manager initialized successfully.');

        // Check if NFC Manager is initialized before configuring P2P mode
        if (!NfcManager.isInitialized) {
          console.warn('NFC Manager not initialized.');
          Alert.alert('Error', 'NFC Manager not initialized.');
          return;
        }

        // Configure NFC for P2P mode (Android Beam)
        await configureNfcForP2PMode();

        // Cleanup when the component is unmounted
        return () => {
          NfcManager.stop();
        };
      } catch (ex) {
        console.warn('Error initializing NFC Manager:', ex);
      }
    }

    initNfc();
  }, []);

  async function configureNfcForP2PMode() {
    try {
      // Request NFC P2P technology
      await NfcManager.requestTechnology(NfcTech.Ndef);

      console.log('NFC P2P mode configured.');
    } catch (ex) {
      console.warn('Error configuring NFC for P2P mode:', ex);
      Alert.alert('Error', 'Failed to configure NFC for P2P mode.');
    }
  }

  async function initiateSharing() {
    try {
      // Check if NFC Manager is initialized
      if (!NfcManager.isInitialized) {
        console.warn('NFC Manager not initialized.');
        Alert.alert('Error', 'NFC Manager not initialized.');
        return;
      }
  
      // Check if NFC technology is available
      if (!NfcManager.ndef) {
        console.warn('NFC technology not available.');
        Alert.alert('Error', 'NFC technology not available.');
        return;
      }
  
      // Start NFC P2P sharing with the AFM number
      const afmNumber = '18109603490';
      const ndefMessage = [
        NfcTech.Ndef,
        NfcManager.ndef.textRecord(afmNumber),
      ];
      await NfcManager.setNdefPushMessage(ndefMessage);
  
      console.log('Sharing initiated with AFM number:', afmNumber);
    } catch (ex) {
      console.warn('Error initiating sharing:', ex);
      Alert.alert('Error', 'Failed to initiate sharing.');
    }
  }
  
  return (
    <View>
      <Text> NFC Writer (Phone as Tag) </Text>
      <Button title="Initiate Sharing" onPress={initiateSharing} />
    </View>
  );
};

export default NFCWriterCom;

我使用 NFC 库用我的 NFC 扫描另一部 NFC 手机并向其传递特定号码,但当我尝试运行它并按下按钮开始共享时,它一直说我 NFC 管理器未初始化。我尝试过很多库,但仍然没有成功。有人知道哪个库或者它如何工作吗?

react-native nfc scanning
1个回答
0
投票

Android Beam 在 Android 10 中被删除并弃用。

因此您无法在 Android 13 测试手机上使用它。

© www.soinside.com 2019 - 2024. All rights reserved.