android:如何检测网络连接到互联网

时间:2013-10-20 12:26:31

标签: android networking

我有这段代码来检查互联网连接。

NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

             //if network is active and have internet connection 
            if(info != null && info.isConnected()==true){


            //Some code


            }

     //if network is inactive or doesn't  have internet connection 
     else   if(info == null || info.isConnected()==false){

               Context context = getApplicationContext();
               CharSequence text = " Bad internet connection.";
               int duration = Toast.LENGTH_LONG;
               Toast toast = Toast.makeText(context, text, duration);
               toast.show();

             }

当我启动程序时,一切正常,打开互联网连接,但当我从我的路由器拔出网线时,在我的应用程序仍然打开wifi,应用程序实现这个(if(info!= null&& info.isConnected()== true))和crash.I不知道为什么这段代码成真。

1 个答案:

答案 0 :(得分:0)

Use this for check condition of network:

if (info!=null && info.isAvailable() && info.isConnected()) {
            return true;
        } else {
            return false; 
        }
}
相关问题