小编典典

不推荐使用 ConnectivityManager getNetworkInfo(int)

all

使用 compileSdkVersion 23 ,但试图支持早至 9。

getNetworkInfo(int)
23
中已弃用。建议使用getAllNetworks()andgetNetworkInfo(Network)代替。但是,这两者都需要至少
API 21。

是否有我们可以在支持包中使用的类来帮助解决这个问题?


阅读 62

收藏
2022-08-19

共1个答案

小编典典

您可以使用:

获取活动网络信息();

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { 
    // connected to the internet
    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
        // connected to wifi
    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
        // connected to mobile data
    }
} else {
    // not connected to the internet
}

或者在开关盒中

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { 
    // connected to the internet
    switch (activeNetwork.getType()) {
        case ConnectivityManager.TYPE_WIFI:
            // connected to wifi
            break;
        case ConnectivityManager.TYPE_MOBILE:
            // connected to mobile data
            break;
        default:
            break;
    }
} else {
    // not connected to the internet
}
2022-08-19