在检测的Android互联网连接问题 [英] Problem in detecting Internet Connection in Android
问题描述
我已经创建了使用谷歌地图一个Android应用程序。现在我要来检查网络连接是否可用。我在谷歌搜索,最后我通过了#1解决方法:
I have created a Android application using Google Maps. Now I want to check whether an internet connection is available or not. I search in Google and finally I got solution through Stackoverflow:
boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo)
{
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
HaveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
HaveConnectedMobile = true;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我已经写了我的网上谷歌地图code,如果它返回true和离线code,如果它返回false。
I have written my online Google map code if it return true and offline code if it return false.
我的问题是它呈现出一个互联网连接可用,即使事实并非如此。哪里有我犯了一个错误?
My problem is its showing an internet connection is available even when it is not. Where have I made a mistake?
推荐答案
尝试使用的NetworkInfo NI = cm.getActiveNetworkInfo();
而不是的NetworkInfo NI = cm.getAllNetworkInfo();
。应该只有一个激活的数据网络在任何一个时间,因为机器人将用最好的可用的并关闭其余节省电池
Try using NetworkInfo ni = cm.getActiveNetworkInfo();
instead of NetworkInfo ni = cm.getAllNetworkInfo();
. There should only be one active data network at any one time because Android will use the best available and shut down the others to conserve battery.
另外,我倾向于使用 ni.isConnectedOrConnecting();
而不是 ni.isConnected();
,因为它可以捕捉过渡态更好。
Also, I tend to use ni.isConnectedOrConnecting();
instead of ni.isConnected();
because it can catch transition states better.
我还用 ni.getType()== ConnectivityManager.TYPE_WIFI
而不是 ni.getTypeName()。equalsIgnoreCase(WIFI)
,因为它是更有效地比较两个 INT
值比它要比较两个字符串。
I also use ni.getType() == ConnectivityManager.TYPE_WIFI
instead of ni.getTypeName().equalsIgnoreCase("WIFI")
because it is much more efficient to compare two int
values than it is to compare two strings.
下面code对我的作品:
The following code works for me:
boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if ( ni != null )
{
if (ni.getType() == ConnectivityManager.TYPE_WIFI)
if (ni.isConnectedOrConnecting())
HaveConnectedWifi = true;
if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
if (ni.isConnectedOrConnecting())
HaveConnectedMobile = true;
}
这篇关于在检测的Android互联网连接问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!