下面是一段Android代码,它可以很好地检查网络是否连接 .
public static boolean isNetworkAvailable(Context context)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
但是,拥有有效的网络接口并不能保证特定的网络服务可用 .
很多时候我们连接到网络但仍然无法访问常见的互联网网络服务,例如,谷歌
常见场景:
-
Android设备连接到Wi-Fi,后来证明是专用网络 . 因此isNetworkAvailable将返回该网络已连接,但无法连接到任何其他服务
-
有时电话信号显示它已连接到服务提供商数据计划 . 所以网络连接是真的,但仍然无法访问谷歌/雅虎 .
One way is to check if "isNetworkAvailable" function returns TRUE, then run following code
HttpGet request = new HttpGet(url));
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
}
}
catch (SocketException e)
{
return "Socket Exceptiopn:" + e.toString();
}
catch (Exception e)
{
return "General Execption:" + e.toString();
}
但我认为这不是一个好方法,因为它可能会耗费大量时间
So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?
3 回答
检查这段代码......它对我有用:)
然后,我定义处理程序:
并启动测试:
代码来自Gilbou https://stackoverflow.com/a/5803489/2603719
我希望我能帮助你
Issue #1:
Android设备连接到Wi-Fi,后来证明是专用网络 .
因此
isNetworkAvailable
将返回该网络已连接,但无法连接到任何其他服务 .Issue #2:
有时电话信号显示它已连接到服务提供商数据计划 . 所以网络连接是真的,但仍然无法访问谷歌/雅虎 .
最终,您需要 Monitor 网络连接的变化,
Step 1:
只需注册
BroadcastReceiver
即可执行以下操作<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
Step 2:
当您在
onReceive(Context context,Intent intent)
方法上获得回调时,请检查连接状态 .即:
boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
//除了
EXTRA_NO_CONNECTIVITY
之外,还有其他参数也可用于监控Reference:
Examples:
Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android
Android-getting-notified-of-connectivity-changes
Github: Example for network-detect-notify
Android Docs:
Connectivity Monitoring
Connectivity Manager
我希望它会有所帮助!!
使用此代码检查互联网连接,它检查设备上的所有互联网连接 . 并且确保你已经在menifest中添加了Internet权限 .