_registerEvents() {
   this._subscriptions = [
     DeviceEventEmitter.addListener('dataChannelStateChanged', ev => {
       if (ev.id !== this.id) {
         return;
       }
       this.readyState = ev.state;
       if (this.readyState === 'open') {
         this.dispatchEvent(new RTCDataChannelEvent('open', {channel: this}));
       } else if (this.readyState === 'close') {
         this.dispatchEvent(new RTCDataChannelEvent('close', {channel: this}));
         this._unregisterEvents();
       }
     }),
     DeviceEventEmitter.addListener('dataChannelReceiveMessage', ev => {
       if (ev.id !== this.id) {
         return;
       }
       let data = ev.data;
       if (ev.type === 'binary') {
         data = base64.toByteArray(ev.data).buffer;
       }
       this.dispatchEvent(new MessageEvent('message', {data}));
     }),
   ];
 }
  constructor (props){
    super(props);
    this.state = {textInput: ''};
    this._onRefresh = this._onRefresh.bind(this);
    this.keyboardWillShowEvent = DeviceEventEmitter.addListener('keyboardWillShow', this.keyboardWillShow.bind(this));
		this.keyboardWillHideEvent = DeviceEventEmitter.addListener('keyboardWillHide', this.keyboardWillHide.bind(this));
  }
 /**
  * Attaches a listener to remote notification events while the app is running
  * in the foreground or the background.
  *
  * Valid events are:
  *
  * - `notification` : Fired when a remote notification is received. The
  *   handler will be invoked with an instance of `PushNotificationIOS`.
  * - `register`: Fired when the user registers for remote notifications. The
  *   handler will be invoked with a hex string representing the deviceToken.
  */
 static addEventListener(type, handler) {
     invariant(
         type === 'notification' || type === 'register' || type === 'localNotification',
         'RNVoipPushNotificationManager only supports `notification`, `register` and `localNotification` events'
     );
     var listener;
     if (type === 'notification') {
         listener = DeviceEventEmitter.addListener(
             DEVICE_NOTIF_EVENT,
             (notifData) => {
                 handler(new RNVoipPushNotification(notifData));
             }
         );
     } else if (type === 'localNotification') {
         listener = DeviceEventEmitter.addListener(
             DEVICE_LOCAL_NOTIF_EVENT,
             (notifData) => {
                 handler(new RNVoipPushNotification(notifData));
             }
         );
     } else if (type === 'register') {
         listener = DeviceEventEmitter.addListener(
             NOTIF_REGISTER_EVENT,
             (registrationInfo) => {
                 handler(registrationInfo.deviceToken);
             }
         );
     }
     _notifHandlers.set(handler, listener);
 }
Example #4
0
    componentWillMount() {
        const { navigator } = this.context;
        DeviceEventEmitter.addListener('OverrideUrl', function(e: Event){
        	if(e.indexOf("code=") > -1){
                var code = e.slice(e.indexOf("code=")+5);
                let promise = new Promise((resolve) => {
                    ajax.getAuthorizationToken(resolve, code);
                });
                promise.then(function(val){
                    console.log("&*&*(&("+JSON.stringify(val));
                    let value = JSON.parse(val);
                    let token={timeStamp: moment().add(60, 'minutes'),
                    token: value.access_token,
                    refreshToken: value.refresh_token};
                    console.log("^&*^*&^*"+JSON.stringify(token));
                    storage.setStorage("ACCESS_TOKEN", token);
                    ajax.getAccountInfo(token.token);
                    navigator.to('settings');

                }.bind(this));
        	}else if(e.indexOf("error=") > -1){
                navigator.to('settings');
            }
        }.bind(this));

        DeviceEventEmitter.addListener('LoadingFinish', function(e: Event){
            this.setState({
                visible: false,
            });
        }.bind(this));
    }
 static addEventListener(type: string, handler: Function) {
   var listener;
   if (type === 'notification') {
     listener =  DeviceEventEmitter.addListener(
       DEVICE_NOTIF_EVENT,
       (notifData) => {
         GcmAndroid.isInForeground = notifData.isInForeground;
         var data = JSON.parse(notifData.dataJSON);
         handler(new GcmAndroid(data));
       }
     );
   } else if (type === 'register') {
     listener = DeviceEventEmitter.addListener(
       NOTIF_REGISTER_EVENT,
       (registrationInfo) => {
         handler(registrationInfo.deviceToken);
       }
     );
   } else if (type === 'registerError') {
     listener = DeviceEventEmitter.addListener(
       NOTIF_REGISTER_ERROR_EVENT,
       (info) => {
         var error = new Error(info.message);
         handler(error);
       }
     );
   }
   _notifHandlers.set(handler, listener);
 }
 componentDidMount(){
     DeviceEventEmitter.addListener(
                      'need_views',
                      this._needViews);
    DeviceEventEmitter.addListener(
                      'end_reached',
                      this._endReached);
 }
Example #7
0
  componentWillMount () {
    // Using keyboardWillShow/Hide looks 1,000 times better, but doesn't work on Android
    // TODO: Revisit this if Android begins to support - https://github.com/facebook/react-native/issues/3468
    DeviceEventEmitter.addListener('keyboardDidShow', this.keyboardDidShow.bind(this))
    DeviceEventEmitter.addListener('keyboardDidHide', this.keyboardDidHide.bind(this))

    // Configure the right nav button
    this.props.navigator.state.tapForgotPassword = this.tapForgotPassword.bind(this)
  }
  componentDidMount() {
    if (this.props.forceFocusField !== this.state.focusedField){
      this._focusField('input_' + this.props.forceFocusField)
    }

    this._listeners = [
      DeviceEventEmitter.addListener(Platform.OS == 'IOS' ? 'keyboardWillShow' : 'keyboardDidShow', this._keyboardWillShow),
      DeviceEventEmitter.addListener(Platform.OS == 'IOS' ? 'keyboardWillHide' : 'keyboardDidHide', this._keyboardWillHide),
    ];
  }
Example #9
0
  async componentWillMount(){
    this.keyboardDidShowListener = DeviceEventEmitter.addListener('keyboardDidShow', this.keyboardDidShow.bind(this));
    this.keyboardDidHideListener = DeviceEventEmitter.addListener('keyboardDidHide', this.keyboardDidHide.bind(this));

    //let cache = await AsyncStorage.getItem(require('../../config/appConfig').cache);
    let cache = await AsyncStorage.getItem('somethingelse');
    if(cache){
      this.props.navigator.resetTo({name:'app'});
    }
  }
 onGoogleSignIn() {
   DeviceEventEmitter.addListener('googleSignIn', (user) => {
     this.setState({ user: user });
     this.sendData();
   });
   DeviceEventEmitter.addListener('googleSignInError', (error) => {
     ToastAndroid.show('Login using google failed', ToastAndroid.SHORT, 2000);
   });
   GoogleSignin.signIn();
 }
 constructor(enforcer) {
   if (enforcer != singletonEnforcer) {
     throw new Error('CannotConstructSingleton');
   }
   super();
   this.handlePhotoViewerDismissed = this.handlePhotoViewerDismissed.bind(this);
   this.handlePhotoViewerActionButtonPress = this.handlePhotoViewerActionButtonPress.bind(this);
   DeviceEventEmitter.addListener(NYTPhotoViewer.ACTION_BUTTON_PRESS, this.handlePhotoViewerActionButtonPress);
   DeviceEventEmitter.addListener(NYTPhotoViewer.DISMISSED, this.handlePhotoViewerDismissed);
 }
Example #12
0
 componentDidMount(){
   DeviceEventEmitter.addListener(
     'regionDidEnter', (data) => {
       this.setState({inRegion: true});
     });
   DeviceEventEmitter.addListener(
     'regionDidExit', (data) => {
       this.setState({inRegion: false});
     });
 }
 componentDidMount() {
   const {dispatch, route} = this.props;
   dispatch(fetchOfficeForm(route.officeFormData.id));
   dispatch(startHandleTimeConsuming());
   if (Platform.OS === 'ios') {
     dispatch(changeKeyboardSpace(0));
     //添加代理事件
     DeviceEventEmitter.addListener('keyboardWillShow', this.updateKeyboardSpace);
     DeviceEventEmitter.addListener('keyboardWillHide', this.resetKeyboardSpace);
   }
 }
    return new Promise((resolve, reject) => {
      const sucessCb = DeviceEventEmitter.addListener('RNGoogleRevokeSuccess', () => {
        this._removeListeners(sucessCb, errorCb);
        resolve();
      });

      const errorCb = DeviceEventEmitter.addListener('RNGoogleRevokeError', (err) => {
        this._removeListeners(sucessCb, errorCb);
        reject(new GoogleSigninError(err.error, err.code));
      });

      RNGoogleSignin.revokeAccess();
    });
	constructor(props) {
		super(props);
		this.state = {
			didFocus: false
		};
		DeviceEventEmitter.addListener('keyboardWillShow', this.updateKeyboardSpace.bind(this));
		DeviceEventEmitter.addListener('keyboardWillHide', this.resetKeyboardSpace.bind(this));

		if (Platform.OS === 'android') {
			DeviceEventEmitter.addListener('keyboardDidShow', this.updateKeyboardSpace.bind(this));
			DeviceEventEmitter.addListener('keyboardDidHide', this.resetKeyboardSpace.bind(this));
		}
	}
 componentDidMount() {
   const {
     turnToNextOne
   } = this.props;
   DeviceEventEmitter.addListener(ON_MEDIA_COMPLETION, () => {
     console.log('播放完成');
     turnToNextOne();//当前先实现顺序循环吧, 单曲循环跟随机播放以后再说
   });
   //进度更新
   DeviceEventEmitter.addListener(MEDIA_PROGRESS_UPDATE, info => {
     this.setState(info);
   });
 }
    return new Promise((resolve, reject) => {
      const sucessCb = DeviceEventEmitter.addListener('RNGoogleSignOutSuccess', () => {
        this._removeListeners(sucessCb, errorCb);
        resolve();
      });

      const errorCb = DeviceEventEmitter.addListener('RNGoogleSignOutError', (err) => {
        this._removeListeners(sucessCb, errorCb);
        reject(new GoogleSigninError(err.error, err.code));
      });

      this._user = null;
      RNGoogleSignin.signOut();
    });
    return new Promise((resolve, reject) => {
      const sucessCb = DeviceEventEmitter.addListener('RNGoogleSignInSilentSuccess', (user) => {
        this._user = user;
        this._removeListeners(sucessCb, errorCb);
        resolve(user);
      });

      const errorCb = DeviceEventEmitter.addListener('RNGoogleSignInSilentError', () => {
        this._removeListeners(sucessCb, errorCb);
        resolve(null);
      });

      RNGoogleSignin.currentUserAsync();
    });
Example #19
0
function UdpSocket(options, onmessage) {
  EventEmitter.call(this)

  if (typeof options === 'string') options = { type: options }

  if (options.type !== 'udp4' && options.type !== 'udp6') {
    throw new Error('invalid udp socket type')
  }

  this.type = options.type
  this._ipv = Number(this.type.slice(3))
  this._ipRegex = ipRegex['v' + this._ipv]({ exact: true })
  this._id = instances++
  this._state = STATE.UNBOUND
  this._subscription = DeviceEventEmitter.addListener(
    'udp-' + this._id + '-data', this._onReceive.bind(this)
  );

  // ensure compatibility with node's EventEmitter
  if (!this.on) this.on = this.addListener.bind(this)

  if (onmessage) this.on('message', onmessage)

  Sockets.createSocket(this._id, {
    type: this.type
  }) // later
}
Example #20
0
export async function watchPositionAsync(options: LocationOptions, callback: LocationCallback) {
  if (!deviceEventSubscription) {
    deviceEventSubscription = DeviceEventEmitter.addListener(
      'Exponent.locationChanged',
      ({ watchId, location }) => {
        const callback = watchCallbacks[watchId];
        if (callback) {
          callback(location);
        } else {
          NativeModules.ExponentLocation.removeWatchAsync(watchId);
        }
      },
    );
  }

  const watchId = nextWatchId++; // XXX: thread safe?
  watchCallbacks[watchId] = callback;
  await NativeModules.ExponentLocation.watchPositionImplAsync(watchId, options);

  let removed = false;
  return {
    remove() {
      if (!removed) {
        NativeModules.ExponentLocation.removeWatchAsync(watchId);
        delete watchCallbacks[watchId];
        removed = true;
      }
    },
  };
}
Example #21
0
 componentDidMount() {
   const { dispatch } = this.props;
   DeviceEventEmitter.addListener('changeCategory', (typeIds) => {
     typeIds.forEach((typeId) => {
       dispatch(readAction.fetchArticles(false, true, typeId));
     });
     this.setState({
       typeIds
     });
   });
   InteractionManager.runAfterInteractions(() => {
     Storage.get('typeIds')
       .then((typeIds) => {
         if (!typeIds) {
           typeIds = [0, 12, 9, 2];
         }
         typeIds.forEach((typeId) => {
           dispatch(readAction.fetchArticles(false, true, typeId));
         });
         this.setState({
           typeIds
         });
       });
   });
 }
Example #22
0
  componentDidMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.goBack);

    const {dispatch} = this.props;

    InteractionManager.runAfterInteractions(() => {
        dispatch(fetchDetail(programId));
    });

    setTimeout(() => {
        this.setState(
          {
            animPlaying: false
          }
        );
    }, 1000);
    
    if (!mDeviceEventEmitter)
    {
      mDeviceEventEmitter = DeviceEventEmitter.addListener(
              'fullScreenCallback',
              (response) => {
                this.changeToFullScreen(response);
              }
      );
    }
  }
Example #23
0
  constructor (host, config) {

    if (typeof host === 'undefined')
      throw 'Hello there! Could you please give socket a host, please.';
    if (typeof config === 'undefined')
      config = {};

    this.sockets = SocketIO;
    this.isConnected = false;
    this.handlers = {};
    this.onAnyHandler = null;

    this.deviceEventSubscription = DeviceEventEmitter.addListener(
      'socketEvent', this._handleEvent.bind(this)
    );

    // Set default handlers
    this.defaultHandlers = {
      connect: () => {
        this.isConnected = true;
      },

      disconnect: () => {
        this.isConnected = false;
      }
    };

    // Set initial configuration
    this.sockets.initialize(host, config);
  }
Example #24
0
 constructor() {
   super();
   this._gcm = GCM;
   DeviceEventEmitter.addListener('GCMEvent', (e) => {
     this.emit(e.type, e.data);
   });
 }
Example #25
0
  constructor() {
    super();
    this.state = {};
    DeviceEventEmitter.addListener('general', (message) => {
      Alert.alert("From Go", message);
    });
    fetch("http://localhost:8080/").then((result) => {
      return result.text();
    }).then((text) => {
      this.setState({ httpMessage: text });
    });
    var ws = new WebSocket('ws://localhost:8080/websocket');

    ws.onopen = () => {
      // connection opened
      ws.send('something');
    };

    ws.onmessage = (e) => {
      this.setState({ webSocketMessage: e.data });
    };
    NativeModules.Go.sayHello((data) => {
      this.setState({nativeBridgeMessage: data});
    });
  }
Example #26
0
  //initGeolocation gets the initial geolocation and set it to initialPosition state
  initGeolocation(initialCameraAngleCallback) {
    //this will listen to geolocation changes and update it in state
    this.getInitialLocation = DeviceEventEmitter.addListener(
      'locationUpdated',
      (location) => {
        this.props.action.updateInitLocation(location.coords);
      }
    );

    //wait 7 seconds to get a more accurate location reading, remove getInitialLocation listner after that
    setTimeout(() => {
      this.getInitialLocation.remove();

      //initial call to server to set initialPosition to 0,0
      let positionObj = {
        latitude: this.props.initialPosition.latitude,
        longitude: this.props.initialPosition.longitude,
        threejsLat: 0,
        threejsLon: 0
      };
      this.props.action.fetchPlaces(positionObj)

      .catch((err) => {
        //implement error message
        setTimeout(() => {this.props.action.fetchPlaces(positionObj)}, 3000);
      });

      initialCameraAngleCallback();
    }, 2000);
  }
Example #27
0
function _getEmitter(): EventEmitter {
  if (!_emitter) {
    _emitter = new EventEmitter();
    DeviceEventEmitter.addListener('Exponent.nativeUpdatesEvent', _emitEvent);
  }
  return _emitter;
}
Example #28
0
    componentDidMount() {
        BleManager.start({showAlert: true});
        try {
            NativeAppEventEmitter
                .addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral.bind(this));
            this.setState({scanning: true});
            this.scanning = setInterval(()=> this.handleScan(), 3000);

            Heading.start(1)
                .then(didStart => {
                    console.log('Heading:', didStart);
                });

            DeviceEventEmitter.addListener('headingUpdated', data => {
                //console.log('New heading is:', data.heading);
                this.currentAzimuth = data.heading - 120;
            });

            this.interval = setInterval(() => {
                this.setState({
                    azimuth: this.currentAzimuth
                });
            }, 100);

            var url = new URL('http://bluenavy.herokuapp.com/path'), params = {src:'335f7b63-8c95-4e4c-87ad-dae5d493d5ec',dest:'82aa8eb8-732d-4488-92b5-ef999343315e'};
            Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
            console.log(url);
            fetch(url.href).then(data=>{return data.json()}).then(data=>console.log(data)).catch(err=>console.log(err));
        } catch (e) {
            console.log(e);
        }
    }
  const remote = (reportStatusDownload) => {
    return {
      async download(downloadProgressCallback) {
        if (!this.downloadUrl) {
          throw new Error("Cannot download an update without a download url");
        }

        let downloadProgressSubscription;
        if (downloadProgressCallback) {
          // Use event subscription to obtain download progress.   
          downloadProgressSubscription = DeviceEventEmitter.addListener(
            "CodePushDownloadProgress",
            downloadProgressCallback
          );
        }
      
        // Use the downloaded package info. Native code will save the package info
        // so that the client knows what the current package version is.
        try {  
          const downloadedPackage = await NativeCodePush.downloadUpdate(this);
          reportStatusDownload && reportStatusDownload(this);
          return { ...downloadedPackage, ...local };
        } finally {
          downloadProgressSubscription && downloadProgressSubscription.remove();
        }
      },
    
      isPending: false // A remote package could never be in a pending state
    };
  };
  componentDidMount() {
    DeviceEventEmitter.addListener('didUpdateDimensions', () => {
      this.photoRefs.map(p => p && p.forceUpdate());
      this.openPage(this.state.currentIndex, false);
    });

    this.openPage(this.state.currentIndex, false);
  }