为了检查互联网连接,我使用此代码:
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//return netInfo != null && netInfo.isConnectedOrConnecting();
return netInfo != null && netInfo.isAvailable() && netInfo.isConnected();
}
这是最常用的代码,我发现无处不在 - 但并不可靠地工作。
这是返回true,虽然我无法使用互联网。
我的手机其他应用正确给消息:“无法连接到互联网”。
编辑1
看来,它在互联网连接有返回true - 即使它是无法用于某些原因。
如果我关掉手机数据/互联网我的手机上 - 那么此方法正确返回false。
Those all will tell you if your device is connected or not, they do not tell you the internet status...
For that you should use this code...
private boolean isOnline() {
try{
// ping to googlevto check internet connectivity
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 80);
socket.connect(socketAddress, 3000);
socket.close();
return true;
} catch (Exception e) {
// internet not working
return false
}
}
You must do this in async task or it will give you network on main thread exception...
I am assuming you are already calling isOnline method in async task.
Well if you are not using this in an async task,
You must use it here like this....
for example you want to go to xyz activity only if internet available
private class GoToXYZActivity extends AsyncTask<String, Void, Void> {
boolean internetAvailable;
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
internetAvailable = inOnline();
return null;
}
protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}
protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
if (internetAvailable)
/// goto xyz activity
else
/// toast - no internet
}
}
And on click event you must call this method
new GoToXYZActivity().execute();
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}