1

I'm using NetInfo to get the connection but some devices android crash with that

LOG:

Error Tag: Mini App Bundle Message: null Stack: android.net.ConnectivityManager$TooManyRequestsException at android.net.ConnectivityManager.convertServiceException(ConnectivityManager.java:3687) at android.net.ConnectivityManager.sendRequestForNetwork(ConnectivityManager.java:3924) at android.net.ConnectivityManager.registerDefaultNetworkCallback(ConnectivityManager.java:4334) at android.net.ConnectivityManager.registerDefaultNetworkCallback(ConnectivityManager.java:4311) at com.reactnativecommunity.netinfo.NetworkCallbackConnectivityReceiver.register(NetworkCallbackConnectivityReceiver.java:42) at com.reactnativecommunity.netinfo.NetInfoModule.initialize(NetInfoModule.java:38) at com.facebook.react.bridge.ModuleHolder.doInitialize(ModuleHolder.java:222) at com.facebook.react.bridge.ModuleHolder.markInitializable(ModuleHolder..java:97) at com.facebook.react.bridge.NativeModuleRegistry.notifyJSInstanceInitialized(NativeModuleRegistry.java:102) at com.facebook.react.bridge.CatalystInstanceImpl$2.run(CatalystInstanceImpl.java:441) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26) at android.os.Looper.loop(Looper.java:237) at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225) at java.lang.Thread.run(Thread.java:919)

In my code:

import MaxApiManager from '@common/MaxApiManager';
import { throttle } from 'lodash';
import React, { useEffect, useState } from 'react';
import { View, TouchableOpacity, Image, StyleSheet, Text } from 'react-native';
import ChatImages from 'src/screens/Chat/img';
import { mapNameWithLocalContact } from 'src/screens/Chat/utils/ChatUtils';
import { Avatar, Skeleton } from '@momo-platform/component-kits';
import NetInfo from '@react-native-community/netinfo';

export function HeaderConversation({
    relationShip,
    relationshipText,
    friendInfo = {},
    goToProfile = () => {},
}) {
    const [isConnected, setIsConnected] = useState(true);

    useEffect(() => {
        NetInfo?.fetch()?.then(state => {
            setIsConnected(state.isConnected);
        });
    }, []);

    return (
        <View style={styles.headerLeft}>
            <TouchableOpacity
                style={styles.buttonBack}
                onPress={throttle(() => MaxApiManager.dismiss(), 1000, {
                    leading: true,
                    trailing: false,
                })}
            >
                <Image source={ChatImages.ic_back} style={styles.icBack} />
            </TouchableOpacity>
            {relationShip || isConnected === false ? (
                <TouchableOpacity onPress={goToProfile} style={styles.info}>
                    <Avatar
                        size="small"
                        name={friendInfo?.name}
                        source={{ uri: friendInfo?.avatar }}
                    />

                    <View style={{ marginLeft: 12 }}>
                        <Text style={styles.txtRoomName}>
                            {mapNameWithLocalContact({
                                phone: friendInfo?.phone,
                                name: friendInfo?.name,
                            })}
                        </Text>
                        {relationShip && <Text>{relationshipText}</Text>}
                    </View>
                </TouchableOpacity>
            ) : (
                <View style={{ paddingTop: 12 }}>
                    <Skeleton.Custom
                        left={<Skeleton.Media size={35} />}
                        style={styles.skeletonItem}
                    >
                        <Skeleton.Line style={styles.width_1_9} />
                        <Skeleton.Line style={styles.width_1_10} />
                    </Skeleton.Custom>
                </View>
            )}
        </View>
    );
}

const styles = StyleSheet.create({
    headerLeft: {
        paddingLeft: 8,
        flexDirection: 'row',
        alignItems: 'center',
    },
    buttonBack: { padding: 8, marginRight: 4 },
    width_1_9: { width: 150, height: 16 },
    width_1_10: { width: 100, height: 12, marginTop: -6 },
    skeletonItem: {
        marginVertical: 5,
    },
    info: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    txtRoomName: { fontSize: 16, fontWeight: 'bold' },
    icBack: { width: 24, height: 24 },
});

AnalyticsModule.js

const AnalyticModule = {
    netInfoSub: null,

    initialize(deviceInfo) {
        UserProfile.getInstance().getData().then((profile) => {
            Storage.getItem("", (ipAddress) => {
                StorageCache.get("").then(location => {
                    if (!this.netInfoSub) {
                        this.netInfoSub = NetInfo.addEventListener((state) => {
                            let netInfo = getNetworkInfo(state);
                            this.TRACKING_NETWORK_INFO = JSON.stringify(netInfo);
                        })
                    }
                })
            })
        })
    },
}

More infor: @react-native-community/netinfo: ^5.9.9 react-native: 0.61.5

Anhdevit
  • 1,926
  • 2
  • 16
  • 29
  • Hi Anhdevit, Can you please post the full code of the component – dhruv soni Dec 24 '20 at 12:57
  • I updated my code – Anhdevit Dec 25 '20 at 06:44
  • Thanks, Did you try to use useNetInfo as per the answer? If that also does not work then we have to look somewhere else – dhruv soni Dec 28 '20 at 14:35
  • Sorry, I updated my code again. We have many modules so I found another module is Analytics Modules we init event listener NetInfo but the event alive the entire life of the app. So in this article, they said max of NetworkCallbacks is 100 http://www.a-hoffmann.me/blog/2019/12/27/how-many-networkcallbacks-are-too-many-looking-at-the-toomanyrequestsexception/ I think it is the reason make my app crash – Anhdevit Dec 29 '20 at 02:39
  • 1
    Oh okay, Then try to unsubscribe the listener. Take look at it here for reference. https://github.com/react-native-netinfo/react-native-netinfo#usage – dhruv soni Dec 29 '20 at 07:37

2 Answers2

1

The easiest way to obtain network status information in your functional component is by using useNetInfo hook

import {useNetInfo} from '@react-native-community/netinfo';

const YourComponent = () => {
  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

for more details on property object: netinfo Docs

imKrishh
  • 762
  • 1
  • 6
  • 11
1

We have an eventListener for NetInfo and the mistake is we don't remove this event and with android, NetworkCallbacks have a limit(Maybe is 100 enter link description here)

Anhdevit
  • 1,926
  • 2
  • 16
  • 29