下面是一段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" />
但拥有有效的网络接口并不能保证特定的网络服务可用。
很多时候我们连接到网络但仍然无法访问常见的互联网网络服务,例如谷歌
常见情景:
一种方法是检查“isNetworkAvailable”函数是否返回TRUE,然后运行以下代码
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();
}
但我认为这不是一个好方法,因为它可能会耗费大量时间
那么有没有其他替代方案(在时间,速度方面)确保我们连接到网络以及可以访问最常见的互联网服务?
答案 0 :(得分:2)
检查此代码......它对我有用:)
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
@Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
@Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
} catch (Exception e) {}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
然后,我定义了处理程序:
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
并启动测试:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
来自Gilbou的代码https://stackoverflow.com/a/5803489/2603719
我希望我可以帮助你
答案 1 :(得分:2)
问题#1:
Android设备连接到Wi-Fi,后来证明是专用网络
因此isNetworkAvailable
将返回该网络已连接,但无法连接到任何其他服务。
问题#2:
有时电话信号显示它已连接到服务提供商数据计划。所以网络连接是真的,但仍然无法访问谷歌/雅虎。
I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2.
最终,您需要监控网络连接中的更改
第1步:
只需注册BroadcastReceiver
即可采取以下措施
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
第2步:
当您在onReceive(Context context,Intent intent)
方法上获得回调时,请检查连接状态。
即:
boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
//除EXTRA_NO_CONNECTIVITY
外,还有其他参数可用于监控
<强>参考:强>
<强>示例:强>
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文档:
我希望它会有所帮助!!
答案 2 :(得分:0)
使用此代码检查互联网连接,检查设备上的所有互联网连接。并且确保你已经在menifest中添加了Internet权限。
boolean flag=false;
ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().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)
{
flag=true;
}
}
if(flag==true)
{
Log.e("TAG","Internet Is Connected");
}
else
{
Log.e("TAG","Internet Is Not Connected");
}