Permalink
Browse files

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 0779dd1e87f6c0c9481f4063e72aafe7805383c6
@@ -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;
@@ -43,6 +43,7 @@ var APIS = [
require('./IntentAndroidExample.android'),
require('./LayoutEventsExample'),
require('./LayoutExample'),
+ require('./NetInfoExample.android'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./TimerExample'),
@@ -68,7 +68,7 @@ var APIS = [
require('./CameraRollExample.ios'),
require('./GeolocationExample'),
require('./LayoutExample'),
- require('./NetInfoExample'),
+ require('./NetInfoExample.ios'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./PushNotificationIOSExample'),
@@ -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"
@@ -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;
@@ -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
*
@@ -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
@@ -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);
@@ -183,7 +187,7 @@ var NetInfo = {
fetch: function(): Promise {
return new Promise((resolve, reject) => {
- RCTNetInfo.getCurrentReachability(
+ RCTNetInfo.getCurrentConnectivity(
function(resp) {
resolve(resp.network_info);
},
@@ -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}];
}
}
@@ -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}]);
Oops, something went wrong.

0 comments on commit 0779dd1

Please sign in to comment.