检查在Android互联网连接 [英] Checking internet connection on android
问题描述
我有以下的code在我的应用程序检查网络连接WIFI / EDGE / GPRS / 3G。
I have the following code for checking internet connection wifi/EDGE/GPRS/3G on my application.
在code是
public static boolean checkConn(Context ctx) {
ConnectivityManager conMgr = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {
return true;
} else if (conMgr.getNetworkInfo(0).getState()==NetworkInfo.State.DISCONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED){
return false;
}
return false;
}
和我称之为象下面这样:
and I am calling it like below :
if (CheckInternet.checkConn(introPage.this) == true) {
Intent toMainPage = new Intent(introPage.this, mainPage.class);
System.gc();
startActivity(toMainPage);
} else if (CheckInternet.checkConn(getApplicationContext()) == false) {
Toast.makeText(getApplicationContext(),
"Sorry, No internet connectivity found", Toast.LENGTH_SHORT)
.show();
}
不过,我有一个问题,那就是如果我连接到无线网络,我打开应用程序,它工作正常,但如果我关闭应用程序,并关闭WiFi和重新打开应用程序,它不通过无连接的错误,我需要关闭我的设备,然后将其打开,而同样的情况是,如果WiFi是关闭了,我打开应用程序时,抛出了无连接的错误,如果我打开它,它仍然抛出无连接的同样的错误,直到除非我关闭和设备。
But I am having an issue, which is that if I am connected to wifi, and I open the application, it works fine, but if I close application and turn off wifi and re-open application, it doesn't through the error of "no connection" , I need to turn off my device and then turn it on, and same case is if wifi is off, and I open application, it throws error of "no connection", and if I turn it on, still it throws the same error of "no connection", until unless I turn off and on device.
推荐答案
有时候主动连接不是第一个在列表中,或者处于非活动状态或处于错误状态。这是我会怎么做:
Sometimes the active connection is not first in the list, or is inactive or in an error state. This is how I would do it:
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
请不要忘记添加此权限的应用程序清单:
Don't forget to add this permission in the application manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
这是否帮助你?
Does this help you?
灵光
这篇关于检查在Android互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!