Display an alert when internet connection not available in android application

后端 未结 13 774
有刺的猬
有刺的猬 2020-12-08 11:48

In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn\'t, it gives an alert

13条回答
  •  青春惊慌失措
    2020-12-08 12:18

    try this

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo datac = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if ((wifi != null & datac != null)
                    && (wifi.isConnected() | datac.isConnected())) {
                    //connection is avlilable
                     }else{
                    //no connection
                      Toast toast = Toast.makeText(context, "No Internet Connection",
                    Toast.LENGTH_LONG);
            toast.show();  
                    }
    

    and don't forget to add following permssions

    
        
    

提交回复
热议问题