如何检查网络可用性?
我必须使用 wifi(如果可用)将我的应用程序与服务器连接, 或 gprs(如果 wifi 不可用)。 这是我检查连接可用性的代码
public static final boolean isConnectionAvailable(Activity a)
{
ConnectivityManager cm = (ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = cm.getNetworkInfo(0).getState();
State wifi = cm.getNetworkInfo(1).getState();
if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
return true;
}
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
return true;
}
return false;
}
这是正确的方法吗?有人可以建议我更好的方法吗?
I have to connect my app with server using either wifi (if it is available),
or gprs (if wifi is not available).
Here is my code to check the connection availability
public static final boolean isConnectionAvailable(Activity a)
{
ConnectivityManager cm = (ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = cm.getNetworkInfo(0).getState();
State wifi = cm.getNetworkInfo(1).getState();
if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
return true;
}
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
return true;
}
return false;
}
Is this a correct way? Can anyone suggest me a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下非常相似的方法有效,但具有不关心底层介质的额外优点,因为它看起来似乎不仅仅支持 WiFi。也许移动设备也涵盖了这些内容,但文档并不是非常清楚:
The following very similar approach works, but has the added advantage of not caring what the underlying medium, since it looks as though there is support for more than just WiFi. Maybe these are also covered by mobile, but the docs aren't super clear:
网络可用性检查:
Network Availability Check :
或者你可以使用一些 kotlin 实现
}
Or you could use some kotlin implementation
}