2013-10-20 159 views
0

我有這段代碼來檢查互聯網連接。android:如何檢測網絡連接到互聯網

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(); 

      } 

當我啓動該程序,一切工作正常與啓用Internet連接,但是當我從我的路由器拔出網線,並在我的應用程序仍然開啓WLAN的應用得到真正的本(如果(info!= null & & info.isConnected()== true))和crash.I不知道爲什麼這段代碼變爲true。

回答

0
Use this for check condition of network: 

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