探秘React Native的全能传感器管理库:react-native-sensor-manager
import React from 'react';
import { Text, View } from 'react-native';
import { SensorManager } from 'react-native-sensor-manager';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
accelerometerData: 'Waiting for data...',
};
}
componentDidMount() {
SensorManager.startAccelerometer(SensorManager.SENSOR_INTERVAL_FASTEST).then(subscription => {
this._accelerometerSubscription = subscription;
this._accelerometerSubscription.onActivate(() => {
console.log('Accelerometer activated');
});
this._accelerometerSubscription.onDeactivate(() => {
console.log('Accelerometer deactivated');
});
this._accelerometerSubscription.onData((data) => {
this.setState({
accelerometerData: `x: ${data.x}, y: ${data.y}, z: ${data.z}`,
});
});
}).catch(error => {
console.error('Accelerometer error:', error);
});
}
componentWillUnmount() {
if (this._accelerometerSubscription) {
this._accelerometerSubscription.remove();
this._accelerometerSubscription = null;
}
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>{this.state.accelerometerData}</Text>
</View>
);
}
}
这段代码展示了如何在React Native应用中使用react-native-sensor-manager
库来监听加速度计数据。代码中使用了生命周期函数componentDidMount
和componentWillUnmount
来处理订阅的创建和清理,以及使用了函数组件而非类组件来简化代码结构。
评论已关闭