如何在react-native中自动启用和禁用离线模式

时间:2018-05-22 04:45:30

标签: android react-native react-native-android

我正在尝试使用react-native代码在android中自动启用和禁用离线模式, 我想知道是否有任何反应原生的可能性, 如果可能,任何人都可以给我一些建议,我该如何实现它。  任何帮助都必须非常感谢。

谢谢。

2 个答案:

答案 0 :(得分:1)

试试此链接https://www.npmjs.com/package/react-native-system-setting

  import SystemSetting from 'react-native-system-setting'

       SystemSetting.isAirplaneEnabled().then((enable)=>{
        const state = enable ? 'On' : 'Off';
        console.log('Current airplane is ' + state);
    })

    SystemSetting.switchAirplane(()=>{
        console.log('switch airplane successfully');
    })

答案 1 :(得分:0)

您可以使用react native Netinfo查找在线和在线设备。请参阅以下链接 https://medium.com/dailyjs/offline-notice-in-react-native-28a8d01e8cd0

import React, { PureComponent } from 'react';
import { View, Text, NetInfo, Dimensions, StyleSheet } from 'react-native';

const { width } = Dimensions.get('window');

function MiniOfflineSign() {
  return (
    <View style={styles.offlineContainer}>
      <Text style={styles.offlineText}>No Internet Connection</Text>
    </View>
  );
}

class OfflineNotice extends PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({ isConnected });
    } else {
      this.setState({ isConnected });
    }
  };

  render() {
    if (!this.state.isConnected) {
      return <MiniOfflineSign />;
    }
    return null;
  }
}

const styles = StyleSheet.create({
  offlineContainer: {
    backgroundColor: '#b52424',
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    width,
    position: 'absolute',
    top: 30
  },
  offlineText: { color: '#fff' }
});

export default OfflineNotice;