Broadcast receiver for checking internet connection in android app

后端 未结 21 3195
温柔的废话
温柔的废话 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:47

    manifest:

    
        
            
        
    
    

    class for receiver:

    public class ConnectivityReceiver extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action) {
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    DebugUtils.logDebug("BROADCAST", "network change");
                    if(NetworkUtils.isConnect()){
                        //do action here
                    }
                break;
            }
        }
    }
    

    and classs utils like example:

    public class NetworkUtils {
    
        public static boolean isConnect() {
            ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Network[] netArray = connectivityManager.getAllNetworks();
                NetworkInfo netInfo;
                for (Network net : netArray) {
                    netInfo = connectivityManager.getNetworkInfo(net);
                    if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                        //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                        Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                        return true;
                    }
                }
            } else {
                if (connectivityManager != null) {
                    @SuppressWarnings("deprecation")
                    NetworkInfo[] netInfoArray = connectivityManager.getAllNetworkInfo();
                    if (netInfoArray != null) {
                        for (NetworkInfo netInfo : netInfoArray) {
                            if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                                //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                                Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
    

提交回复
热议问题