我正在尝试检查网络是否可用。
但在我的模拟器中它总是显示connected
(在断开互联网后)
我的代码有什么错误吗?我正在使用wifi连接。
代码:
public class AndroidConnectivityActivity extends Activity
{
Button checkBtn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBtn = (Button) findViewById(R.id.button1);
checkBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(isInternetOn())
{
Toast.makeText(getBaseContext(), "Connected",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Not connected",
Toast.LENGTH_SHORT).show();
}
}});
}
public final boolean isInternetOn()
{
ConnectivityManager connec = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE);
if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)
||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING)
||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))
{
return true;
}
else if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED)
|| (connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED))
{
return false;
}
return false;
}
}