且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测Android上是否有可用的互联网连接

更新时间:2022-05-24 09:07:33

ConnectivityManagergetActiveNetworkInfo() 方法返回一个 NetworkInfo 实例,表示它可以找到的第一个连接的网络接口或 null 如果没有连接任何接口.检查此方法是否返回 null 应该足以判断互联网连接是否可用.

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

您还需要:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在你的安卓清单中.

请注意,拥有活动网络接口并不能保证特定的网络服务可用.网络问题、服务器停机、低信号、强制门户、内容过滤器等都会阻止您的应用程序到达服务器.例如,在您收到 Twitter 服务的有效响应之前,您无法确定您的应用是否可以访问 Twitter.

Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.