我尝试下面的代码检查连接性:
public static NetworkInfo getNetworkInfo(Context context) {
if (context == null)
return null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected())
return activeNetwork;
else {
for (Network n: cm.getAllNetworks()) {
NetworkInfo nInfo = cm.getNetworkInfo(n);
if(nInfo != null && nInfo.isConnected())
return nInfo;
}
}
return activeNetwork;
}
public static boolean isConnectivityAllowed(Context context) {
NetworkInfo info = NetworkUtils.getNetworkInfo(context);
return info != null && info.isConnected();
}
通常,它可以正常工作,但在某些情况下,即使我有连接,它也会返回断开连接。搜索,测试,检查日志后,我了解如果我运行该应用程序时设备的电池电量不足,则该函数返回断开连接,因为操作系统将系统置于省电模式,然后如果我更改了连接,该应用程序将获得正确的答案。 @phil的答案中有更多信息here。
打开节电器时,有人知道如何检查连接吗?!
在AndroidManifest.xml中添加以下权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
创建用于连接检查的NetworkUtils类
public class NetworkUtils {
/**
* Check if mobile data is enabled
*
* @return mobile data on or off
*/
private static boolean isMobileDataEnabled(Context context) {
Context ctx = context.getApplicationContext();
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
return (Boolean) cm.getClass().getMethod("getMobileDataEnabled").invoke(cm, new Object[0]);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return false;
}
/**
* Check if connected to wifi network
*
* @return wifi connected or not
*/
private static boolean isWifiConnected(Context context) {
WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wm != null && wm.isWifiEnabled() && wm.getConnectionInfo().getNetworkId() != -1;
}
/**
* Check if mobile data is on or device is connected to wifi network
*/
public static boolean isConnected(Context context) {
return isMobileDataEnabled(context) || isWifiConnected(context);
}}
调用NetworkUtils.isConnected()以进行使用
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check connectivity
boolean isConnected = NetworkUtils.isConnected(this);
}}