componentWillMount() { // 设置网络状态监听 // 这么写是没问题的,不过要注意,如果用在listener中,那么每次bind后返回的都是一个新的对象,所以是不合适的 // NetInfo.addEventListener('statusChange', this._statusChange.bind(this)); // 这么写需要全局that,或者箭头函数方式实现 NetInfo.addEventListener('statusChange', this._statusChange); // 设置当前网络连接状态监听 NetInfo.isConnected.addEventListener('connectChange', this._connectChange); // 获取当前网络的状态,比如 Wifi,cell(3G LTE) NONE NetInfo.fetch().done((connectionInfo) => { this.setState({ connectionInfo: connectionInfo, }) }); // 获取当前网络的连接状态 NetInfo.isConnected.fetch().done((isConnected) => { this.setState({ isConnected: isConnected, }) }) }
componentDidMount() { //网络是否连接的监听 //addEventListener(eventName:ChangeEventName,handler:Function) //静态方法,用设置网络变化事件监听器,同时需要传入回调的处理方法 NetInfo.isConnected.addEventListener( 'isConnected', this._handleConnectivityChange ); //网络连接转台变化的监听 NetInfo.addEventListener( 'statusChange', this._handleNetStatusChange ); //检测网络是否连接 NetInfo.isConnected.fetch().done( (isConnected) => {this.setState({isConnected});} ); //检测网络连接信息,这只到state中,触发render函数 NetInfo.fetch().done( (connectionInfo) => {this.setState({connectionInfo});} ); }
componentWillMount() { if(Platform.OS==='android') { BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid.bind(this)); } NetInfo.addEventListener('change',this.handleConnectionInfoChange.bind(this)); NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange.bind(this)); //获取网络当前信息 NetInfo.fetch().done((connectionInfo) => { var info=this.switchConnectionInfo(connectionInfo); this.props.dispatch(ChangeNetInfo(info)); }); //获取网络当前连接状态 NetInfo.isConnected.fetch().then((isConnected) => { this.props.dispatch(ChangeNetConnectStatus(isConnected)); }); //获取网络当前连接计费状态 NetInfo.isConnectionExpensive().then((isConnectionExpensive) => { this.props.dispatch(ChangeNetExpensiveStatus(isConnectionExpensive)); }); Ionicons.getImageSource('ios-arrow-back', 30, '#fff').then((source) => this.setState({ backButtonImage: source })); Ionicons.getImageSource('md-menu', 30, '#fff').then((source) => this.setState({ drawerImage: source })); }
componentDidMount () { NetInfo.isConnected.addEventListener('change', this.setConnected) NetInfo.isConnected.fetch().done(this.setConnected) NetInfo.addEventListener('change', this.setConnectionInfo) NetInfo.fetch().done(this.setConnectionInfo) NetInfo.addEventListener('change', this.updateConnectionInfoHistory) }
export const doDeviceInfo = () => dispatch => { const deviceUniqueID = DeviceInfo.getUniqueID(); const deviceName = DeviceInfo.getDeviceName(); dispatch(gotDeviceInfo({ uniqueID: deviceUniqueID })); dispatch(gotDeviceUniqueID({ deviceUniqueID: `${DeviceInfo.getManufacturer()}-${deviceUniqueID}` })); dispatch(gotDeviceName({ deviceName })); // Network information const handleNetReachabilityChange = (reachability) => { if (reachability === 'none' || reachability === 'NONE') reachability = null; if (reachability === 'unknown' || reachability === 'UNKNOWN') reachability = undefined; if (reachability === 'cell') reachability = 'mobile'; if (typeof reachability === 'string') reachability = reachability.toLowerCase(); dispatch(gotDeviceInfo({ networkReachability: reachability })); }; NetInfo.fetch().done(handleNetReachabilityChange); NetInfo.addEventListener('change', handleNetReachabilityChange); const handleNetConnectivityChange = (isConnected) => { dispatch(gotDeviceInfo({ networkConnectivity: isConnected })); }; NetInfo.isConnected.fetch().done(handleNetConnectivityChange); NetInfo.isConnected.addEventListener('change', handleNetConnectivityChange); // UI variables var windowWidth = Dimensions.get('window').width; var windowHeight = Dimensions.get('window').height; dispatch(gotDeviceInfo({ windowWidth, windowHeight })); var pixelRatio = PixelRatio.get(); dispatch(gotDeviceInfo({ pixelRatio })); if (NativeModules.SystemWindowAndroid) { NativeModules.SystemWindowAndroid.isTranslucentStatusBar((e) => { console.error('doDeviceInfo error', e); }, (translucentStatusBar) => { dispatch(gotDeviceInfo({ translucentStatusBar: translucentStatusBar })); }); NativeModules.SystemWindowAndroid.isTranslucentActionBar((e) => { console.error('doDeviceInfo error', e); }, (translucentActionBar) => { dispatch(gotDeviceInfo({ translucentActionBar: translucentActionBar })); }); NativeModules.SystemWindowAndroid.getStatusBarHeight((e) => { console.error('doDeviceInfo error', e); }, (statusBarHeight) => { dispatch(gotDeviceInfo({ statusBarHeight: statusBarHeight / PixelRatio.get() })); }); NativeModules.SystemWindowAndroid.getActionBarHeight((e) => { console.error('doDeviceInfo error', e); }, (actionBarHeight) => { dispatch(gotDeviceInfo({ actionBarHeight: actionBarHeight / PixelRatio.get() })); }); } };
componentWillMount() { NetInfo.addEventListener(TAG, this._netInfoListener); NetInfo.fetch().done((netInfo) => { this.setState({ netWorkInfo: netInfo }); }); }
componentWillUnmount(){ NetInfo.removeEventListener( 'change', this._handleConnectionInfoChange.bind(this) ); NetInfo.fetch().done((connectionInfo)=>{ this.setNetState(connectionInfo); }); }
componentDidMount () { NetInfo.addEventListener( 'change', this._handleConnectionInfoChange ); NetInfo.fetch().done( (connectionInfo) => { this.setState({connectionInfo}); } ); }
// Listen for changes in network connectivity _setupNetInfoListener() { NetInfo.getConnectionInfo().then(connectionInfo => { this.props.debug && console.log('[networkState]', connectionInfo.type) this.setState({ networkState: connectionInfo.type }) }) NetInfo.addEventListener( 'connectionChange', this._onConnectionChange.bind(this) ) }
componentDidMount() { AppState.addEventListener('change', this.onAppState) this.onAppState(AppState.currentState) NetInfo.addEventListener('change', this.onNetInfo) NetInfo.fetch().done((netInfo) => this.onNetInfo(netInfo)) NetInfo.isConnected.addEventListener('change', this.onConnectivityChange) NetInfo.isConnected.fetch().done(this.onConnectivityChange) this._keyboardDidHide = Keyboard.addListener('keyboardDidHide', () => this.onKeyboard(false)) this._keyboardDidShow = Keyboard.addListener('keyboardDidShow', (layout) => this.onKeyboard(true, layout)) }
reload() { NetInfo.fetch().done((netInfo) => { this.setState({ netWorkInfo: netInfo }); }); }
componentWillUnmount() { AppState.removeEventListener('change', this.onAppState) NetInfo.removeEventListener('change', this.onNetInfo) NetInfo.isConnected.removeEventListener('change', this.onConnectivityChange) this._keyboardDidHide.remove() this._keyboardDidShow.remove() }
componentWillUnmount() { if(Platform.OS==='android') { BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid.bind(this)); } NetInfo.removeEventListener('change',this.handleConnectionInfoChange.bind(this)); NetInfo.isConnected.removeEventListener('change',this.handleConnectivityChange.bind(this)); }
handleConnectionInfoChange(connectionInfo) { var info=this.switchConnectionInfo(connectionInfo); this.props.dispatch(ChangeNetInfo(info)); NetInfo.isConnectionExpensive().then((isConnectionExpensive) => { this.props.dispatch(ChangeNetExpensiveStatus(isConnectionExpensive)); }); }
_setIsConnectionExpensive = async () => { try { this._isConnectionExpensive = await NetInfo.isConnectionExpensive(); } catch (err) { // err means that isConnectionExpensive is not supported in iOS this._isConnectionExpensive = null; } };
componentWillUnmount: function() { PushNotificationIOS.removeEventListener('notification'); AppStateIOS.removeEventListener('change'); RCTDeviceEventEmitter.removeEventListener('loadCartCount'); RCTDeviceEventEmitter.removeEventListener('showPlanSwitch'); RCTDeviceEventEmitter.removeEventListener('loadNotice'); NetInfo.removeEventListener('change', this._handleConnectionInfoChange); },
checkIfExpensive = () => { NetInfo.isConnectionExpensive().then( isConnectionExpensive => { this.setState({ isConnectionExpensive:isConnectionExpensive, }); } ); };
componentWillUnmount() { NetInfo.isConnected.removeEventListener( 'isConnected', this._handleConnectivityChange ); NetInfo.removeEventListener( 'statusChange', this._handleNetStatusChange ); }
componentWillUnmount() { NetInfo.removeEventListener( 'connectionChange', this.handleConnectionInfoChange ); NetInfo.isConnected.removeEventListener( 'connectionChange', this.handleConnectionisConnected ); };
test('能够正常监听网络状态的变化', done => { const networkType = '3g' const networkCb = (res) => { expect(res).toEqual({ networkType, isConnected: true }) done() } expect.assertions(1) Taro.onNetworkStatusChange(networkCb) NetInfo.changeNetworkType('cellular', networkType) })
/** * Adds listeners for when connection reachability and app state changes to update props * @returns {void} * @private */ _addListeners() { NetInfo.addEventListener('connectionChange', connectionInfo => { this._setShouldInitUpdateReach(false); this._update(connectionInfo.type); }); AppState.addEventListener('change', async () => { this._setShouldInitUpdateReach(false); const connectionInfo = await NetInfo.getConnectionInfo(); this._update(connectionInfo.type); }); }
test('能返回正确的关于网络状态的判断', done => { const networkType = 'none' const networkCb = (res) => { expect(res).toEqual({ networkType, isConnected: false }) done() } expect.assertions(1) Taro.onNetworkStatusChange(networkCb) NetInfo.changeNetworkType('none') })
componentDidMount() { // drawer reference will only be available when component finishes mounting // the Root component will be fire componentDidMount after all child has mounted // setState here so its child component Toolbar could get an updated reference of the Drawer Instance this.setState({ drawerInstance: this.drawer }); let {dispatch} = this.props; // since we need to add event handlers here for NetInfo, does not delegate this into an action // should be better moved to splash screen for checking network NetInfo.addEventListener('change', this._handleConnectionInfoChange.bind(this)); NetInfo.fetch().done((connection) => { this.connectionHistory.unshift(connection); console.log('main app componentDidMount checkpoint: ', connection); // default connection state is 'WIFI', just to save one more dispatch -> render roundtrip if (connection === 'NONE') { dispatch(updateNetworkStatus(connection)); } }); }
ImagePickerManager.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { _this.props.actPushingDone(); console.log('User cancelled image picker'); } else if (response.error) { _this.props.actPushingDone(); console.log('ImagePickerManager Error: ', response.error); } else { // You can display the image using either data: _this.props.actPushing(); var imageuri = response.uri; shareLinkContent.photos[0].imageUrl=imageuri; console.log(shareLinkContent); NetInfo.fetch().done((reach) => { console.log(reach); //Subir fotos solo por wifi if("WIFI"==reach||"wifi"==reach||"CELL"==reach||"cell"==reach||"MOBILE"==reach||"mobile"==reach){ console.log('connected to the internet!') ShareDialog.canShow(shareLinkContent).then( function(canShow) { if (canShow) { return ShareDialog.show(shareLinkContent); }else{ console.log("No se pudo compartir"); _this.submitSelfie(imageuri); } } ).then( function(result) { if (result.isCancelled) { console.log('Share cancelled'); } else { _this.submitSelfie(imageuri); } }, function(error) { console.log("Error al compartir "+error); console.log("Error al compartir "+imageuri); _this.submitSelfie(imageuri); } ); } else { console.log("no hay internet"); _this.submitSelfie(imageuri); } }); } });
checkInternetConnection() { NetInfo.getConnectionInfo() .then( ( connectionInfo ) => { if ( connectionInfo.type === "none" || connectionInfo.type === "unknown" ) { this.setError( "internet" ); this.fetchSpeciesId(); } this.setError( null ); } ).catch( ( err ) => { console.log( err, "can't check connection" ); } ); }
export function shouldSync() { return NetInfo .fetch() .then((reach=> { if (__DEV__) return false; if (Platform.OS === 'ios') { return reach === 'wifi'; } else { return ['WIFI', 'VPN'].indexOf(reach) > -1; } })); }
componentDidMount() { NetInfo.addEventListener( 'connectionChange', this.handleConnectionInfoChange ); NetInfo.getConnectionInfo().done( (connectionInfo) => { this.setState({ connectionInfo:connectionInfo, }); } ); NetInfo.isConnected.addEventListener( 'connectionChange', this.handleConnectionisConnected ); NetInfo.isConnected.fetch().done( (isConnected) => { this.setState({ isConnected, }); } ); };
init: client => { const explicitlyDisabled = client.config.connectivityBreadcrumbsEnabled === false const implicitlyDisabled = client.config.autoBreadcrumbs === false && client.config.connectivityBreadcrumbsEnabled !== true if (explicitlyDisabled || implicitlyDisabled) return NetInfo.addEventListener('connectionChange', ({ type, effectiveType }) => { client.leaveBreadcrumb( `Connectivity changed`, { type, effectiveType }, 'state' ) }) },
refreshUserActividades() { var _this = this; //Actualizar actividades si hace falta if(!this.props.actividadesUser.actualizadas) { console.log("Actividades desactualizadas, si hay internet se actualizarán") NetInfo.fetch().done((reach) => { console.log(reach); //Actualizar actividades si hay internet if("WIFI"==reach||"wifi"==reach||"CELL"==reach||"cell"==reach||"MOBILE"==reach||"mobile"==reach){ console.log("Actividades desactualizadas, se actualizarán"); _this.props.loadUserActividades(_this.props.user.currentRally.grupo.idGrupo); } }); } }
}).catch((err)=>{ //下载 NetInfo.fetch().done((reach) => { if(reach!="WIFI"){ Alert.alert( '提示', `检测到当前设备出在非WIFI网络环境下\n是否继续下载?`, [ {text: '取消'}, {text: '确定', onPress: () =>this.downloadFiles()} ] ) }else{ this.downloadFiles() } }) }