1. To view the current network status of the mobile phone, obtain the ConnectionManager

    1. ConnectionManager way
 /** * Checks whether there is a network connection, but returns true * if the connected network is not available@param mContext
     * @return* /
    public static boolean isNetConnection(Context mContext) {
        if(mContext! =null){
            ConnectivityManager connectivityManager = 
                          (ConnectivityManager) mContext.
                          getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            boolean connected = networkInfo.isConnected();
            if(networkInfo! =null&&connected){
                if (networkInfo.getState()== NetworkInfo.State.CONNECTED){
                    return true;
                }else{
                    return false; }}}return false;
    }

Copy the code
    1. NetworkCapabilities (above 6.0)

NetworkCapabilities is a new class added to API 21. NetworkCapabilities does not have much information on its own, but describes NetworkCapabilities and transport types. NetworkCapabilities provides a way to determine whether a current network is available, and it’s not time consuming.


  /** * Check whether the current network is available (version 6.0 or later) * real-time *@param context
     * @return* /
    public static boolean isNetSystemUsable(Context context) {
        boolean isNetUsable = false;
        ConnectivityManager manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkCapabilities networkCapabilities =
                    manager.getNetworkCapabilities(manager.getActiveNetwork());
            if(networkCapabilities ! =null) { isNetUsable = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); }}return isNetUsable;
    }

Copy the code





2. If there is a network connection, check whether the network can be accessed normally

Note: this method need to be in the child thread calls, otherwise an error: android.os.Net workOnMainThreadException



 /** * Function: check whether the current URL is connectable or valid, * description: connect to the network for a maximum of X times, if x times are unsuccessful, the address is considered to be unavailable *@returnTrue indicates that Internet access is available, false indicates that Internet access is disabled */
    private static URL url;
    private static HttpURLConnection con;
    private static int state = -1;
    public static boolean isNetOnline(a) {
        After Android 4.0, HTTP requests cannot be made in the main thread
        int counts = 0;
        boolean isNetsOnline = true;
        while (counts < 2) {
            try {
                url = new URL("https://www.baidu.com");
                con = (HttpURLConnection) url.openConnection();
                state = con.getResponseCode();
                Log.e("FragmentNet"."isNetOnline counts: " + counts + "=state: " + state);
                if (state == 200) {
                    isNetsOnline = true;
                }
                break;
            } catch (Exception ex) {
                isNetsOnline = false;
                counts++;
                Log.e("FragmentNet"."IsNetOnline URL unavailable, connection no." + counts + "Time");
                continue; }}return isNetsOnline;

    }

Copy the code


3. Ping network mode

Note: Ping is the most common and universal way to determine a network. The biggest disadvantage of this method is that it takes a long time. I have calculated that the ping time is about 10 seconds for each ping and 11 seconds for each ping. Although this method is time-consuming, it is the most commonly used method and there is no better alternative.

Sometimes this extreme happens when we’re connected to a WiFi or cable that doesn’t have an external connection,

Currently, the Android SDK does not recognize this, and the general solution is to ping an external network

    / * * *@categoryCheck whether there is an extranet connection (common methods cannot determine whether the extranet network is connected, such as connecting to the LAN) *@return* /
    public static final boolean ping(a) {

        String result = null;
        try {
            String ip = "www.baidu.com";// The ping address can be changed to any reliable extranet
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping the url 3 times
            // Read the contents of ping without adding
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while((content = in.readLine()) ! =null) {
                stringBuffer.append(content);
            }

// Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // Ping status
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed"; }}catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
// Log.d("----result---", "result = " + result);
        }
        return false;
    }
Copy the code
  • Although the mainstream mobile phone system is 6.0 or above, there are always some “old phones” still use 5.0 or even 4.4 or above. To accommodate the problem, Method 1 is still the dominant approach, and this is where Android development is most troublesome.

  • In addition, the ping method can determine the availability of the current network.

Process. The waitFor () returns0, the current network can return process.waitfor ()1The wifi process.waitfor () that requires web authentication returns2The current network is unavailableCopy the code

– About wifi that requires web authentication:

Alert 360wifi!!

In fact, 360wifi itself does not require authentication, after connecting to the network can be directly used. But when the method is used, process.waitfor () returns1. Some mobile systems, such as Meizu, automatically open their browsers when they detect that the current wifi requires web page authentication. This is a very user-friendly design in itself, but will be used by some enterprises, after connecting to wifi, automatically jump to the AD page. So if you use 360wifi to verify, you're lucky, after all360Ah.Copy the code


Four, solve workOnMainThreadException at android.os.Net

1. The Android 4.0 above, the network connection cannot be put on the main thread, or it will error workOnMainThreadException at android.os.Net. However, under version 4.0, errors will not be reported.

In Android4.0, HTTP requests written in the main thread (Activity) will generate errors. This is because Android4.0 allows applications to plication Not Response (ANR) errors. Android is designed to prevent network requests from taking too long and causing the interface to stagnate.

There are two ways to solve this problem:

1. Add code to the Activity’s onCreate() method for small network requests like this

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
Copy the code

2. Start a thread to make your network request. This is recommended

After Android 4.0, HTTP requests cannot be made in the main thread
new Thread(new Runnable(){
         @Override
         public void run(a) {
               cachedImage = asyncImageLoader.loadDrawable(imageUrl, position);
               imageView.setImageDrawable(cachedImage);
         }
 }).start();
Copy the code