How to check the internet connectivity within the network in Android (using internet of some other device through HOTSPOT)

后端 未结 2 1377
独厮守ぢ
独厮守ぢ 2020-12-29 06:58

I have a requirement where I want to check whether there is any internet connectivity when I am connected with the network.

For example, I have device A and device B

2条回答
  •  粉色の甜心
    2020-12-29 07:11

    Try the below function to check your internet connection:

        public static boolean isInternetConnected(Context mContext) {
    
            try {
                ConnectivityManager connect = null;
                connect = (ConnectivityManager) mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
    
                if (connect != null) {
                    NetworkInfo resultMobile = connect
                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    
                    NetworkInfo resultWifi = connect
                            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
                    if ((resultMobile != null && resultMobile
                            .isConnectedOrConnecting())
                            || (resultWifi != null && resultWifi
                                    .isConnectedOrConnecting())) {
                        return true;
                    } else {
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return false;
        }
    

    Add the following permissions to your manifest file,

      
      
    

提交回复
热议问题