javascriptandroidreact-nativebluetooth-lowenergyreact-native-ble-plx

how to maintain bluetooth device connection throughout the react native app


I'm new to react native, I've created an app using react native, I'm working on a Bluetooth device that connects with the app and gives me data.. everything is working fine. but I want the device to stay connected through out the app. but not on a single page.. since I need the device to give me data on specific buttons clicked on different pages.

is there a way to do it

thank you so much.

I tried to connect on a single page it worked absolutely fine, but if navigated to a separate page the device connection is lost, and again have to connect to read data.

ive used react native ble-plx library.


Solution

  • you should do this in root of your project that accessible to all over

    create a new sperate file in root ./src

    const subscription = manager.onStateChange((state) => {
          if (state === 'PoweredOn') {
              this.scanAndConnect();
              subscription.remove();
          }
      }, true);
      return () => subscription.remove();
    }, [manager]);
    

    import this file in main root container of app like below

     <SafeAreaProvider>
          <NavigationContainer>
            <View>
              <AppRoot />
              <Bluetooth /> // connection file import 
            </View>
          </NavigationContainer>
        </SafeAreaProvider>