Android: Check network and real internet connectivity

前端 未结 3 1570
暖寄归人
暖寄归人 2020-12-12 00:51

Below is the piece of Android code which works fine to check if network is connected or not.

public static boolean isNetworkAvailable(Context context) 
{
            


        
3条回答
  •  囚心锁ツ
    2020-12-12 01:26

    Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.

            boolean flag=false;
            ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().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)
                        {
                            flag=true;
    
                        }
    
            }
            if(flag==true)
            {
                 Log.e("TAG","Internet Is Connected");
            }
            else
            {
                  Log.e("TAG","Internet Is Not Connected");
            }
    

提交回复
热议问题