探索React Native的蓝牙经典连接:react-native-bluetooth-classic
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import RNBluetoothClassic, { EVENT_CONNECTION_LOST } from 'react-native-bluetooth-classic';
export default function App() {
const [status, setStatus] = useState('Disconnected');
useEffect(() => {
RNBluetoothClassic.init();
RNBluetoothClassic.on(EVENT_CONNECTION_LOST, () => {
setStatus('Connection Lost');
});
// 在组件卸载时清理资源
return () => {
RNBluetoothClassic.destroy();
};
}, []);
const connectToDevice = async (device) => {
try {
const connected = await RNBluetoothClassic.connect(device);
if (connected) {
setStatus('Connected');
} else {
setStatus('Connection Failed');
}
} catch (error) {
console.error('Connection error:', error);
setStatus('Connection Failed');
}
};
// 假设有一个获取蓝牙设备列表的函数
const devices = getBluetoothDevices();
return (
<View style={styles.container}>
<Text style={styles.status}>{status}</Text>
{devices.map((device) => (
<Text key={device.address} onPress={() => connectToDevice(device)}>
{device.name} ({device.address})
</Text>
))}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
status: {
marginBottom: 20,
},
});
这个代码示例展示了如何在React Native应用中使用react-native-bluetooth-classic
库来管理蓝牙经典连接。它首先初始化蓝牙模块,并设置一个事件监听器来处理连接丢失的情况。然后,它提供了一个连接到蓝牙设备的函数,并在用户点击设备名称时尝试建立连接。最后,它列出了可用的蓝牙设备供用户选择。
评论已关闭