0

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

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 时,应用程序会实现这一点(如果(信息!= null && 信息.isConnected()==true)) 和崩溃。我不知道为什么这段代码是真的。

4

1 回答 1

0
Use this for check condition of network:

if (info!=null && info.isAvailable() && info.isConnected()) {
            return true;
        } else {
            return false; 
        }
}
于 2013-10-20T12:54:04.740 回答