What is the correct way of checking for mobile network available (no data connection)

后端 未结 6 663
名媛妹妹
名媛妹妹 2021-02-02 15:35

What is the correct way of checking if a mobile network (GSM) connection is available on Android? (>2.1) I don\'t want to check if there is data connection available over the mo

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 16:28

    I am using following method to check the availability of network connection in android. The best thing is you can copy this method as it is and can use it to check network connectivity. It checks the connectivity of all networks to ensure whether any of the network is connected or not.

    /**
     * Check the hardware if there are connected to Internet or not.
     * This method gets the list of all available networks and if any one of 
     * them is connected returns true. If none is connected returns false.
     * 
     * @param context {@link Context} of the app.
     * @return true if connected or false if not
     */
    public static boolean isNetworkAvailable(Context context) {
        boolean available = false;
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null) {
                    for (int i = 0; i < info.length; i++) {
                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                            available = true;
                        }
                    }
                }
            }
            if (available == false) {
                NetworkInfo wiMax = connectivity.getNetworkInfo(6);
    
                if (wiMax != null && wiMax.isConnected()) {
                    available = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return available;
    }
    

提交回复
热议问题