Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Open source the Android NetInfo module
Reviewed By: mkonicek

Differential Revision: D2703432

fb-gh-sync-id: 4a85844f1734ec433df543c89f0fdd56fe5db13c
  • Loading branch information
bestander authored and facebook-github-bot-4 committed Dec 2, 2015
1 parent 06f2c33 commit 0779dd1
Show file tree
Hide file tree
Showing 9 changed files with 347 additions and 27 deletions.
158 changes: 158 additions & 0 deletions Examples/UIExplorer/NetInfoExample.android.js
@@ -0,0 +1,158 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';

const React = require('react-native');
const {
NetInfo, // requires android.permission.ACCESS_NETWORK_STATE
Text,
View
} = React;
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');

const ConnectionSubscription = React.createClass({
getInitialState() {
return {
connectionHistory: [],
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleConnectionChange
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleConnectionChange
);
},
_handleConnectionChange: function(netInfo) {
var connectionHistory = this.state.connectionHistory.slice();
connectionHistory.push(netInfo);
this.setState({
connectionHistory,
});
},
render() {
return (
<Text>{JSON.stringify(this.state.connectionHistory)}</Text>
);
}
});

const ConnectionCurrent = React.createClass({
getInitialState() {
return {
netInfo: null,
};
},
componentDidMount: function() {
NetInfo.addEventListener(
'change',
this._handleConnectionChange
);
NetInfo.fetch().done(
(netInfo) => { this.setState({netInfo}); }
);
},
componentWillUnmount: function() {
NetInfo.removeEventListener(
'change',
this._handleConnectionChange
);
},
_handleConnectionChange: function(netInfo) {
this.setState({
netInfo,
});
},
render() {
return (
<Text>{JSON.stringify(this.state.netInfo)}</Text>
);
}
});

const IsConnected = React.createClass({
getInitialState() {
return {
isConnected: null,
};
},
componentDidMount: function() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
},
componentWillUnmount: function() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
},
_handleConnectivityChange: function(isConnected) {
this.setState({
isConnected,
});
},
render() {
return (
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
);
}
});

const NetInfoExample = React.createClass({
statics: {
title: '<NetInfo>',
description: 'Monitor network status.'
},

getInitialState() {
return {
isMetered: null,
};
},
render() {
return (
<View >
<Text> Is Connected: <IsConnected /> </Text>
<Text> Current Connection Type: <ConnectionCurrent /> </Text>
<Text> Connection History: <ConnectionSubscription /> </Text>
<TouchableWithoutFeedback onPress={this.isConnectionMetered}>
<View>
<Text>Click to see if connection is metered: {this.state.isMetered}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
},
isConnectionMetered: function() {
NetInfo.isConnectionMetered((isConnectionMetered) => {
this.setState({
isMetered: isConnectionMetered ? 'Is Metered' : 'Is Not Metered',
});
});
}
});

module.exports = NetInfoExample;
File renamed without changes.
1 change: 1 addition & 0 deletions Examples/UIExplorer/UIExplorerList.android.js
Expand Up @@ -43,6 +43,7 @@ var APIS = [
require('./IntentAndroidExample.android'),
require('./LayoutEventsExample'),
require('./LayoutExample'),
require('./NetInfoExample.android'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./TimerExample'),
Expand Down
2 changes: 1 addition & 1 deletion Examples/UIExplorer/UIExplorerList.ios.js
Expand Up @@ -68,7 +68,7 @@ var APIS = [
require('./CameraRollExample.ios'),
require('./GeolocationExample'),
require('./LayoutExample'),
require('./NetInfoExample'),
require('./NetInfoExample.ios'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./PushNotificationIOSExample'),
Expand Down
Expand Up @@ -3,6 +3,7 @@
package="com.facebook.react.uiapp" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
Expand Down
52 changes: 28 additions & 24 deletions Libraries/Network/NetInfo.js
Expand Up @@ -17,7 +17,7 @@ var Platform = require('Platform');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var RCTNetInfo = NativeModules.NetInfo;

var DEVICE_REACHABILITY_EVENT = 'reachabilityDidChange';
var DEVICE_CONNECTIVITY_EVENT = 'networkStatusDidChange';

type ChangeEventName = $Enum<{
change: string;
Expand Down Expand Up @@ -53,6 +53,26 @@ type ConnectivityStateAndroid = $Enum<{
UNKNOWN: string;
}>;


var _subscriptions = new Map();

if (Platform.OS === 'ios') {
var _isConnected = function(
reachability: ReachabilityStateIOS
): bool {
return reachability !== 'none' &&
reachability !== 'unknown';
};
} else if (Platform.OS === 'android') {
var _isConnected = function(
connectionType: ConnectivityStateAndroid
): bool {
return connectionType !== 'NONE' && connectionType !== 'UNKNOWN';
};
}

var _isConnectedSubscriptions = new Map();

/**
* NetInfo exposes info about online/offline status
*
Expand Down Expand Up @@ -84,6 +104,10 @@ type ConnectivityStateAndroid = $Enum<{
*
* ### Android
*
* To request network info, you need to add the following line to your
* app's `AndroidManifest.xml`:
*
* `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />`
* Asynchronously determine if the device is connected and details about that connection.
*
* Android Connectivity Types
Expand Down Expand Up @@ -135,35 +159,15 @@ type ConnectivityStateAndroid = $Enum<{
* );
* ```
*/

var _subscriptions = new Map();

if (Platform.OS === 'ios') {
var _isConnected = function(
reachability: ReachabilityStateIOS
): bool {
return reachability !== 'none' &&
reachability !== 'unknown';
};
} else if (Platform.OS === 'android') {
var _isConnected = function(
connectionType: ConnectivityStateAndroid
): bool {
return connectionType !== 'NONE' && connectionType !== 'UNKNOWN';
};
}

var _isConnectedSubscriptions = new Map();

var NetInfo = {
addEventListener: function (
eventName: ChangeEventName,
handler: Function
): void {
var listener = RCTDeviceEventEmitter.addListener(
DEVICE_REACHABILITY_EVENT,
DEVICE_CONNECTIVITY_EVENT,
(appStateData) => {
handler(appStateData.network_reachability);
handler(appStateData.network_info);
}
);
_subscriptions.set(handler, listener);
Expand All @@ -183,7 +187,7 @@ var NetInfo = {

fetch: function(): Promise {
return new Promise((resolve, reject) => {
RCTNetInfo.getCurrentReachability(
RCTNetInfo.getCurrentConnectivity(
function(resp) {
resolve(resp.network_info);
},
Expand Down
4 changes: 2 additions & 2 deletions Libraries/Network/RCTNetInfo.m
Expand Up @@ -51,7 +51,7 @@ static void RCTReachabilityCallback(__unused SCNetworkReachabilityRef target, SC

if (![status isEqualToString:self->_status]) {
self->_status = status;
[self->_bridge.eventDispatcher sendDeviceEventWithName:@"networkDidChange"
[self->_bridge.eventDispatcher sendDeviceEventWithName:@"networkStatusDidChange"
body:@{@"network_info": status}];
}
}
Expand Down Expand Up @@ -87,7 +87,7 @@ - (void)dealloc
#pragma mark - Public API

// TODO: remove error callback - not needed except by Subscribable interface
RCT_EXPORT_METHOD(getCurrentReachability:(RCTResponseSenderBlock)getSuccess
RCT_EXPORT_METHOD(getCurrentConnectivity:(RCTResponseSenderBlock)getSuccess
withErrorCallback:(__unused RCTResponseSenderBlock)getError)
{
getSuccess(@[@{@"network_info": _status}]);
Expand Down

0 comments on commit 0779dd1

Please sign in to comment.