我通过使用以下代码了解互联网连接。当应用程序为前台时,NetworkInfo
的连接状态为CONNECTED
,但应用程序为后台或已终止,即使电话已连接3G,连接状态也为DISCONNECTED/BLOCKED
。
我通过stackoverflow看了another questions,但这个问题没有答案。
public class InternetConnectionControl {
private NetworkInfo networkInfo;
private NetworkInfo getNetworkInfo() {
if (networkInfo == null) {
ConnectivityManager _cm = ServiceUtil.getConnectivityManager(MyApplication.getContext());
networkInfo = _cm.getActiveNetworkInfo();
}
return networkInfo;
}
public void setNetworkInfo(NetworkInfo networkInfo) {
this.networkInfo = networkInfo;
}
private boolean isConnectedToWifi() {
NetworkInfo info = getNetworkInfo();
return (info != null && info.isConnectedOrConnecting() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
private boolean isConnectedToMobile() {
NetworkInfo info = getNetworkInfo();
return (info != null && info.isConnectedOrConnecting() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
public boolean isConnectedToInternet() {
boolean isWifiConnected = isConnectedToWifi();
boolean isMobileConnected = isConnectedToMobile();
return isWifiConnected || isMobileConnected;
}
}
答案 0 :(得分:1)
您的设备是三星吗?三星具有省电模式,您必须允许以下方式运行您的应用程序:
第1步
第二步