且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

互联网连接检查在android系统发生故障

更新时间:2022-10-17 16:53:30

 公共类checkconnection {    公共静态布尔checkInternetConnection(上下文的背景下){
        布尔haveConnectedWifi = FALSE;
        布尔haveConnectedMobile = FALSE;        ConnectivityManager厘米=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        尝试{
            的NetworkInfo [] = NetInfo的cm.getAllNetworkInfo();
            对于(NI的NetworkInfo:NetInfo的){
                如果(ni.getTypeName()。equalsIgnoreCase(WIFI))
                    如果(ni.isConnected())
                        haveConnectedWifi = TRUE;
                如果(ni.getTypeName()。equalsIgnoreCase(手机))
                    如果(ni.isConnected())
                        haveConnectedMobile = TRUE;
            }
        }赶上(例外五){
            e.getStackTrace();
        }
        返回haveConnectedWifi || haveConnectedMobile;
    }
}

您拨打登录之前,请使用以下 checkInternetConnection()方法在你的类。 真正确保您已连接。

I am working on an application that needs to communicate with the server. Hence, the check for the internet connectivity is implemented.

The check works perfectly fine when I am working with mobile data and wifi.

The issue is my device is connected with hotspot. I click on the login button and get the progress bar that states "Connecting to the server". Now, I turn off the hotspot. But the wifi is enabled in my device.

(It simply fails to get any responseCode).

My application gets into the infinite state.

Any suggestions of how to overcome this problem.

public class checkconnection {

    public static boolean checkInternetConnection(Context context) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        haveConnectedWifi = true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        haveConnectedMobile = true;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return haveConnectedWifi || haveConnectedMobile;
    }


}

Use the following checkInternetConnection() method in your class before you call the login. true ensures that you have connectivity.