对于Android,网络状态始终为true.如何? [英] Network status is always true for android. How?
本文介绍了对于Android,网络状态始终为true.如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的android应用程序中检查网络状态.
I'm trying to check the network status in my android application.
我有这样的代码:
public boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected())
return true;
return false;
}
当预期的网络可用时,此代码将返回true
,但即使网络不可用,该代码也将重试true
.
This code is returning true
when network is available as expected but it is also returing true
even in case of network not-available.
在两种情况下都只需将其返回的true
放进去!
Simply put its returning true
for both the cases!
我在代码中哪里出错了?
Where I'm making the mistake in the code?
请注意,我是在模拟器中运行该应用程序的.
Note that I run the app in my emulator.
谢谢.
推荐答案
尝试以下方法对我来说很棒.我希望它也会对您有所帮助.
Try out below method it works awesome for me. I hope it will help you also.
public static boolean IsNetConnected()
{
boolean NetConnected = false;
try
{
ConnectivityManager connectivity =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
NetConnected = false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++)
{
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
NetConnected = true;
}
}
}
}
}
catch (Exception e)
{
NetConnected = false;
}
return NetConnected;
}
这篇关于对于Android,网络状态始终为true.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文