Android - 在 ConnectivityManager 的帮助下检查互联网、wifi 和 GPRS 状态?

Android - check internet, wifi and GPRS status with the help of ConnectivityManager?

我读到 "ConnectivityManager" class 提供了有关网络的信息。但是我对如何实现代码感到困惑。我需要一种同时检查互联网、wifi 和 GPRS 的有效方法。 谢谢

再一次:http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION 你必须做点什么,没有人会为你编写完整的代码。阅读文档,您就会知道事件何时触发以及您必须解决哪些问题。

就用这个功能吧。在您想检查互联网是否可用的地方调用此功能。

public boolean isNetworkConnected(Context mContext) {
    final String DEBUG_TAG = "NetworkStatusExample";
    ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(CONNECTIVITY_SERVICE);
    boolean isWifiConn=false;
    boolean isMobileConn=false;
    Network nn=connMgr.getActiveNetwork();
    Network[] networkinf=connMgr.getAllNetworks();
    for (int a=0;a<networkinf.length;a++) {
        NetworkCapabilities networkCapabilities = connMgr.getNetworkCapabilities(networkinf[a]);
        if (networkCapabilities.hasTransport(networkCapabilities.TRANSPORT_CELLULAR)){
            isMobileConn=true;
        }
        else if (networkCapabilities.hasTransport(networkCapabilities.TRANSPORT_WIFI)){
            isWifiConn=true;
        }
    }
    Log.i(DEBUG_TAG, "Wifi connected: " + isWifiConn);
    Log.i(DEBUG_TAG, "Mobile connected: " + isMobileConn);
    editor.putBoolean("isConnected",isMobileConn);
    editor.apply();
    if (isMobileConn || isWifiConn){
        Log.i(DEBUG_TAG, "Network Status..." + isMobileConn);
        return true;
    }
    else {
        return false;
    }
}