在我开始下载某些文件之前,我有这个代码块用于测试是否存在网络连接。我遇到的问题是我也在需要基于网络登录表格的网络上进行测试(类似于酒店,机场甚至飞机)。我正在使用的这段代码对于这种情况完全没用。在这些情况下,网络会报告isAvailable
和isConnected
。这当然是个问题,因为我启动了失败的异步网络连接。我想知道是否有人知道我能做些什么来确保我“真正”联系,或者如果有人对这个问题有任何建议。
这是我的代码块:
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
Log.e("", "Network info: "+networkInfo+" toString?: "+networkInfo.toString());
Log.e("", "getTypeName: "+networkInfo.getTypeName());
Log.e("", "isAvailable: "+networkInfo.isAvailable());
Log.e("", "isConnected: "+networkInfo.isConnected());
以下是我尝试使用我的代码块和结果的用例。
Network info: NetworkInfo: type: mobile[CDMA - 1xRTT], state: CONNECTED/CONNECTED, reason: connected, extra: , roaming: false, failover: true, isAvailable: true, isConnectedToProvisioningNetwork: false
toString?: NetworkInfo: type: mobile[CDMA - 1xRTT], state: CONNECTED/CONNECTED, reason: connected, extra: , roaming: false, failover: true, isAvailable: true, isConnectedToProvisioningNetwork: false
getTypeName: mobile
isAvailable: true
isConnected: true
Network info: NetworkInfo: type: mobile[CDMA - eHRPD], state: CONNECTED/CONNECTED, reason: linkPropertiesChanged, extra: VZWINTERNET, roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
toString?: NetworkInfo: type: mobile[CDMA - eHRPD], state: CONNECTED/CONNECTED, reason: linkPropertiesChanged, extra: VZWINTERNET, roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
getTypeName: mobile
isAvailable: true
isConnected: true
Crash: networkInfo NullPointerException
Crash: networkInfo NullPointerException
Network info: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
toString: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
getTypeName: WIFI
isAvailable: true
isConnected: true
Network info: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "myWifi", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
toString?: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "myWifi", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
getTypeName: WIFI
isAvailable: true
isConnected: true
Network info: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
toString?: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
getTypeName: WIFI
isAvailable: true
isConnected: true
Network info: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "myWifi", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
toString?: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "myWifi", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
getTypeName: WIFI
isAvailable: true
isConnected: true
正如您所看到的,在我使用未经身份验证的Wifi和经过身份验证的Wifi的情况下,我对isAvailable
和isConnected
都是正确的。
答案 0 :(得分:0)
检查这是否适合您。我是这样做的:
创建两个java文件,如下所示:
NetworkConnectivity.java
package com.connectivity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
public class NetworkConnectivity {
private static NetworkConnectivity sharedNetworkConnectivity = null;
private Activity activity = null;
private final Handler handler = new Handler();
private Runnable runnable = null;
private boolean stopRequested = false;
private boolean monitorStarted = false;
private static final int NETWORK_CONNECTION_YES = 1;
private static final int NETWORK_CONNECTION_NO = -1;
private static final int NETWORK_CONNECTION_UKNOWN = 0;
private int connected = NETWORK_CONNECTION_UKNOWN;
public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000;
public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000;
private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>();
private NetworkConnectivity() {
}
public synchronized static NetworkConnectivity sharedNetworkConnectivity() {
if (sharedNetworkConnectivity == null) {
sharedNetworkConnectivity = new NetworkConnectivity();
}
return sharedNetworkConnectivity;
}
public void configure(Activity activity) {
this.activity = activity;
}
public synchronized boolean startNetworkMonitor() {
if (this.activity == null) {
return false;
}
if (monitorStarted) {
return true;
}
stopRequested = false;
monitorStarted = true;
(new Thread(new Runnable() {
@Override
public void run() {
doCheckConnection();
}
})).start();
return true;
}
public synchronized void stopNetworkMonitor() {
stopRequested = true;
monitorStarted = false;
}
public void addNetworkMonitorListener(NetworkMonitorListener l) {
this.networkMonitorListeners.add(l);
this.notifyNetworkMonitorListener(l);
}
public boolean removeNetworkMonitorListener(NetworkMonitorListener l) {
return this.networkMonitorListeners.remove(l);
}
private void doCheckConnection() {
if (stopRequested) {
runnable = null;
return;
}
final boolean connectedBool = this.isConnected();
final int _connected = (connectedBool ? NETWORK_CONNECTION_YES
: NETWORK_CONNECTION_NO);
if (this.connected != _connected) {
this.connected = _connected;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
notifyNetworkMonitorListeners();
}
});
}
runnable = new Runnable() {
@Override
public void run() {
doCheckConnection();
}
};
handler.postDelayed(runnable,
(connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS
: MONITOR_RATE_WHEN_DISCONNECTED_MS));
}
public boolean isConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
private void notifyNetworkMonitorListener(NetworkMonitorListener l) {
try {
if (this.connected == NETWORK_CONNECTION_YES) {
l.connectionEstablished();
} else if (this.connected == NETWORK_CONNECTION_NO) {
l.connectionLost();
} else {
l.connectionCheckInProgress();
}
} catch (Exception e) {
}
}
private void notifyNetworkMonitorListeners() {
for (NetworkMonitorListener l : this.networkMonitorListeners) {
this.notifyNetworkMonitorListener(l);
}
}
}
NetworkMonitorListener.java
package com.connectivity;
public interface NetworkMonitorListener {
public void connectionEstablished();
public void connectionLost();
public void connectionCheckInProgress();
}
最后,用法:
NetworkConnectivity.sharedNetworkConnectivity().configure(this);
NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor();
NetworkConnectivity.sharedNetworkConnectivity()
.addNetworkMonitorListener(new NetworkMonitorListener() {
@Override
public void connectionCheckInProgress() {
// Okay to make UI updates (check-in-progress is rare)
}
@Override
public void connectionEstablished() {
// Okay to make UI updates -- do something now that
// connection is avaialble
Toast.makeText(getBaseContext(), "Connection established", Toast.LENGTH_SHORT).show();
}
@Override
public void connectionLost() {
// Okay to make UI updates -- bummer, no connection
Toast.makeText(getBaseContext(), "Connection lost.", Toast.LENGTH_LONG).show();
}
});
通过上述用法,您可以在运行时检查互联网连接。一旦互联网连接丢失,将出现Toast
(根据上述代码)。
答案 1 :(得分:-1)
试试这个: -
private boolean hasInternetAccess() {
boolean hasInternetAccess = false;
try {
//I set google but you can try anything "reliable"...
//isReachable(1) the timeout in seconds
hasInternetAccess = InetAddress.getByName("www.google.com").isReachable(1);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hasInternetAccess;
}
并使用此
If(WifiConnected() && hasInternetAccess()){
//Do background Work...
}