Broadcast receiver for checking internet connection in android app

后端 未结 21 3196
温柔的废话
温柔的废话 2020-11-21 22:28

I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get

21条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 22:45

    public static boolean isNetworkAvailable(Context context) {
            boolean isMobile = false, isWifi = false;
    
            NetworkInfo[] infoAvailableNetworks = getConnectivityManagerInstance(
                    context).getAllNetworkInfo();
    
            if (infoAvailableNetworks != null) {
                for (NetworkInfo network : infoAvailableNetworks) {
    
                    if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                        if (network.isConnected() && network.isAvailable())
                            isWifi = true;
                    }
                    if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                        if (network.isConnected() && network.isAvailable())
                            isMobile = true;
                    }
                }
            }
    
            return isMobile || isWifi;
        }
    
    /* You can write such method somewhere in utility class and call it NetworkChangeReceiver like below */
    public class NetworkChangedReceiver extends BroadcastReceiver 
    {
    @Override
        public void onReceive(Context context, Intent intent) {
    
            if (isNetworkAvailable(context)) 
                    {
                 Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
    
    
        }
        }
    }
    

    This above broadcast receiver will be called only when Network state change to connected and not on disconnected.

提交回复
热议问题