react-native#DeviceEventEmitter TypeScript Examples

The following examples show how to use react-native#DeviceEventEmitter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From react-native-actions-sheet with MIT License 6 votes vote down vote up
componentDidMount() {
    this.props.id && SheetManager.add(this.props.id);

    this.keyboardShowSubscription = Keyboard.addListener(
      Platform.OS === "android" ? "keyboardDidShow" : "keyboardWillShow",
      this._onKeyboardShow
    );

    this.KeyboardHideSubscription = Keyboard.addListener(
      Platform.OS === "android" ? "keyboardDidHide" : "keyboardWillHide",
      this._onKeyboardHide
    );
    if (this.props.id) {
      this.sheetManagerShowEvent = DeviceEventEmitter.addListener(
        `show_${this.props.id}`,
        this.onSheetManagerShow
      );
      this.sheetManagerHideEvent = DeviceEventEmitter.addListener(
        `hide_${this.props.id}`,
        this.onSheetMangerHide
      );
    }
  }
Example #2
Source File: sheetmanager.tsx    From react-native-actions-sheet with MIT License 6 votes vote down vote up
/**
   * Show an ActionSheet with a given id.
   *
   * @param id id of the ActionSheet to show
   * @param data Any data to pass to the ActionSheet. Will be available from `onBeforeShow` prop.
   */
  static show(id: string, data?: unknown) {
    DeviceEventEmitter.emit(`show_${id}`, data);
  }
Example #3
Source File: sheetmanager.tsx    From react-native-actions-sheet with MIT License 6 votes vote down vote up
/**
   * An async hide function. This is useful when you want to show one ActionSheet after closing another.
   *
   * @param id id of the ActionSheet to show
   * @param data An data to pass to the ActionSheet. Will be available from `onClose` prop.
   */
  static async hide(id: string, data?: unknown): Promise<boolean> {
    return new Promise((resolve) => {
      let sub: EmitterSubscription;
      const fn = () => {
        resolve(true);
        sub?.remove();
      };
      sub = DeviceEventEmitter.addListener(`onclose_${id}`, fn);
      DeviceEventEmitter.emit(`hide_${id}`, data);
    });
  }
Example #4
Source File: contact-tracing-provider.tsx    From SQUID with MIT License 6 votes vote down vote up
/**
   * Initialize Listeners
   */
  registerListeners() {
    // Register Event Emitter
    if (Platform.OS == 'ios') {
      console.log('add listener')
      this.advertiserEventSubscription = eventEmitter.addListener(
        'AdvertiserMessage',
        this.onAdvertiserMessageReceived,
      )

      this.nearbyDeviceFoundEventSubscription = eventEmitter.addListener(
        'NearbyDeviceFound',
        this.onNearbyDeviceFoundReceived,
      )

      this.nearbyBeaconFoundEventSubscription = eventEmitter.addListener(
        'NearbyBeaconFound',
        this.onNearbyBeaconFoundReceived,
      )
    } else {
      console.log('add listener')
      this.advertiserEventSubscription = DeviceEventEmitter.addListener(
        'AdvertiserMessage',
        this.onAdvertiserMessageReceived,
      )

      this.nearbyDeviceFoundEventSubscription = DeviceEventEmitter.addListener(
        'NearbyDeviceFound',
        this.onNearbyDeviceFoundReceived,
      )

      this.nearbyBeaconFoundEventSubscription = DeviceEventEmitter.addListener(
        'NearbyBeaconFound',
        this.onNearbyBeaconFoundReceived,
      )
    }
  }
Example #5
Source File: index.tsx    From react-native-actions-sheet with MIT License 5 votes vote down vote up
_hideAnimation(data: unknown) {
    let {
      animated,
      closeAnimationDuration,
      bottomOffset,
      initialOffsetFromBottom,
      extraScroll,
      closable,
    } = this.props;
    Animated.parallel([
      Animated.timing(this.opacityValue, {
        toValue: closable ? 0 : 1,
        duration: animated ? closeAnimationDuration : 1,
        useNativeDriver: true,
      }),
      Animated.timing(this.transformValue, {
        toValue: closable ? this.actionSheetHeight * 2 : 0,
        duration: animated ? closeAnimationDuration : 1,
        useNativeDriver: true,
      }),
    ]).start();

    waitAsync((closeAnimationDuration ?? 300) / 1.5).then(() => {
      if (!closable) {
        if (bottomOffset && bottomOffset > 0) {
          this.snapToOffset(bottomOffset);
        } else {
          this._scrollTo(
            this.actionSheetHeight * (initialOffsetFromBottom ?? 1) +
              this.state.deviceHeight * 0.1 +
              (extraScroll ?? 0),
            true
          );
          this.currentOffsetFromBottom = initialOffsetFromBottom ?? 1;
        }

        this.isClosing = false;
      } else {
        this._scrollTo(0, false);
        this.currentOffsetFromBottom = initialOffsetFromBottom ?? 1;
        this.setState(
          {
            modalVisible: !closable,
          },
          () => {
            this.isClosing = false;
            this.isReachedTop = false;
            this.props.onPositionChanged && this.props.onPositionChanged(false);
            this.indicatorTranslateY.setValue(-this.state.paddingTop);
            this.layoutHasCalled = false;
            this.deviceLayoutCalled = false;
            this.props.onClose && this.props.onClose(data);
            if (this.props.id) {
              DeviceEventEmitter.emit(`onclose_${this.props.id}`, data);
            }
          }
        );
      }
    });
  }
Example #6
Source File: sheetmanager.tsx    From react-native-actions-sheet with MIT License 5 votes vote down vote up
/**
   * Hide all the opened ActionSheets.
   */
  static hideAll() {
    ids.forEach((id) => DeviceEventEmitter.emit(`hide_${id}`));
  }
Example #7
Source File: ScanHome.tsx    From hamagen-react-native with MIT License 4 votes vote down vote up
ScanHome: FunctionComponent<ScanHomeProps> = (
  {
    navigation,
    route,
    isRTL,
    strings,
    locale,
    languages,
    externalUrls,
    exposures,
    pastExposures,
    firstPoint,
    enableBle,
    batteryDisabled,
    hideLocationHistory,
    checkForceUpdate,
    checkIfHideLocationHistory,
    checkIfBleEnabled,
    checkIfBatteryDisabled
  }
) => {
  const appStateStatus = useRef<AppStateStatus>('active');
  const [{ hasLocation, hasNetwork, hasGPS }, setIsConnected] = useState({ hasLocation: true, hasNetwork: true, hasGPS: true });

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    checkIfHideLocationHistory();
    checkIfBatteryDisabled();
    checkConnectionStatusOnLoad();
    checkIfBleEnabled();
    SplashScreen.hide();

    if (exposures.length > 0) {
      navigation.navigate('ExposureDetected');
    } else {
      checkForceUpdate();

      await goToFilterDrivingIfNeeded(navigation);

      const url = await Linking.getInitialURL();


      if (url) {
        return onOpenedFromDeepLink(url, navigation);
      }

      await syncLocationsDBOnLocationEvent();
    }
  };

  useEffect(() => {
    AppState.addEventListener('change', onAppStateChange);
    NetInfo.addEventListener((state: NetInfoState) => setIsConnected({ hasLocation, hasNetwork: state.isConnected, hasGPS }));
    DeviceEventEmitter.addListener(RNSettings.GPS_PROVIDER_EVENT, handleGPSProviderEvent);

    return () => {
      AppState.removeEventListener('change', onAppStateChange);
      DeviceEventEmitter.removeListener(RNSettings.GPS_PROVIDER_EVENT, handleGPSProviderEvent);
    };
  }, [hasLocation, hasNetwork, hasGPS]);

  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        BackHandler.exitApp();
        return true;
      };

      BackHandler.addEventListener('hardwareBackPress', onBackPress);

      return () => {
        BackHandler.removeEventListener('hardwareBackPress', onBackPress);
      };
    }, [])
  );

  const checkConnectionStatusOnLoad = async () => {
    const locationPermission = await checkLocationPermissions();
    const networkStatus = await NetInfo.fetch();
    const GPSStatus = await RNSettings.getSetting(RNSettings.LOCATION_SETTING);

    setIsConnected({ hasLocation: locationPermission === RESULTS.GRANTED, hasNetwork: networkStatus.isConnected, hasGPS: GPSStatus === RNSettings.ENABLED });
  };

  const onAppStateChange = async (state: AppStateStatus) => {
    if (state === 'active' && appStateStatus.current !== 'active') {
      checkIfHideLocationHistory();
      checkConnectionStatusOnLoad();
      checkIfBatteryDisabled();
    }

    appStateStatus.current = state;
  };

  const handleGPSProviderEvent = (e: any) => {
    setIsConnected({ hasLocation, hasNetwork, hasGPS: e[RNSettings.LOCATION_SETTING] === RNSettings.ENABLED });
  };

  const exposureState = () => {
    // user never got any exposure detected
    if (exposures.length + pastExposures.length === 0) {
      return 'pristine';
    }

    // check if user past exposures are relevant
    // ie: is less then 14 days old
    if (exposures.some(isAfter14Days) || pastExposures.some(isAfter14Days)) {
      return 'relevant';
    }

    return 'notRelevant';
  };


  const RelevantState = () => {
    if (!hasGPS || !hasLocation) return (<NoGPS {...strings.scanHome.noGPS} />);
    if (!hasNetwork) return (<NoNetwork {...strings.scanHome.noNetwork} />);
    return (
      <NoExposures
        isRTL={isRTL}
        strings={strings}
        firstPoint={firstPoint}
        exposureState={exposureState()}
        hideLocationHistory={hideLocationHistory}
        enableBle={enableBle}
        batteryDisabled={batteryDisabled}
        locale={locale}
        languages={languages}
        externalUrls={externalUrls}
        goToLocationHistory={() => navigation.navigate('LocationHistory')}
        goToBluetoothPermission={() => navigation.navigate('Bluetooth')}
        goToBatteryPermission={() => navigation.navigate('Battery')}
        showBleInfo={route.params?.showBleInfo}
      />
    );
  };


  return (
    <View style={styles.container}>
      <ScanHomeHeader
        enableBle={enableBle}
        languages={languages}
        isRTL={isRTL}
        locale={locale}
        externalUrls={externalUrls}
        strings={strings}
        openDrawer={navigation.openDrawer}
      />
      {RelevantState()}
    </View>
  );
}
Example #8
Source File: ContactTracer.tsx    From SQUID with MIT License 4 votes vote down vote up
componentDidMount() {
    console.log(NativeModules.ContactTracerModule)

    // Get saved user ID or generate a new one
    // TODO: Use the global userId instead of the local one. Remove User.tsx file if done
    const userId = nanoid().substr(0, 20)
    this.setState({ userId: userId })
    NativeModules.ContactTracerModule.setUserId(userId).then(userId => {})

    // Check if Tracer Service has been enabled
    NativeModules.ContactTracerModule.isTracerServiceEnabled()
      .then(enabled => {
        this.setState({
          isServiceEnabled: enabled,
        })
        // Refresh Tracer Service Status in case the service is down
        NativeModules.ContactTracerModule.refreshTracerServiceStatus()
      })
      .then(() => {})

    // Check if BLE is available
    NativeModules.ContactTracerModule.initialize()
      .then(result => {
        return NativeModules.ContactTracerModule.isBLEAvailable()
      })
      // For NativeModules.ContactTracerModule.isBLEAvailable()
      .then(isBLEAvailable => {
        if (isBLEAvailable) {
          this.appendStatusText('BLE is available')
          // BLE is available, continue requesting Location Permission
          return requestLocationPermission()
        } else {
          // BLE is not available, don't do anything furthur since BLE is required
          this.appendStatusText('BLE is NOT available')
        }
      })
      // For requestLocationPermission()
      .then(locationPermissionGranted => {
        this.setState({
          isLocationPermissionGranted: locationPermissionGranted,
        })
        if (locationPermissionGranted) {
          // Location permission is granted, try turning on Bluetooth now
          this.appendStatusText('Location permission is granted')
          return NativeModules.ContactTracerModule.tryToTurnBluetoothOn()
        } else {
          // Location permission is required, we cannot continue working without this permission
          this.appendStatusText('Location permission is NOT granted')
        }
      })
      // For NativeModules.ContactTracerModule.tryToTurnBluetoothOn()
      .then(bluetoothOn => {
        this.setState({
          isBluetoothOn: bluetoothOn,
        })

        if (bluetoothOn) {
          this.appendStatusText('Bluetooth is On')
          // See if Multiple Advertisement is supported
          // Refresh Tracer Service Status in case the service is down
          NativeModules.ContactTracerModule.refreshTracerServiceStatus()
          return NativeModules.ContactTracerModule.isMultipleAdvertisementSupported()
        } else {
          this.appendStatusText('Bluetooth is Off')
        }
      })
      // For NativeModules.ContactTracerModule.isMultipleAdvertisementSupported()
      .then(supported => {
        if (supported)
          this.appendStatusText('Multitple Advertisement is supported')
        else this.appendStatusText('Multitple Advertisement is NOT supported')
      })

    // Register Event Emitter
    if (Platform.OS == 'ios') {
      this.advertiserEventSubscription = eventEmitter.addListener(
        'AdvertiserMessage',
        this.onAdvertiserMessageReceived,
      )

      this.nearbyDeviceFoundEventSubscription = eventEmitter.addListener(
        'NearbyDeviceFound',
        this.onNearbyDeviceFoundReceived,
      )
    } else {
      this.advertiserEventSubscription = DeviceEventEmitter.addListener(
        'AdvertiserMessage',
        this.onAdvertiserMessageReceived,
      )

      this.nearbyDeviceFoundEventSubscription = DeviceEventEmitter.addListener(
        'NearbyDeviceFound',
        this.onNearbyDeviceFoundReceived,
      )
    }
  }