本文介绍了ConnectivityManager getNetworkInfo(int) 已弃用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 compileSdkVersion 23,但尝试支持最早的版本 9.

Using compileSdkVersion 23, however trying to support as far back as 9.

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

getNetworkInfo(int) was deprecated in 23. The suggestion was to use getAllNetworks() and getNetworkInfo(Network) instead. However both of these require minimum of API 21.

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

Is there a class that we can use in the support package that can assist with this?

我知道在之前提出了一个解决方案,但是我对 API 最低要求 9 的挑战带来了问题.

I know that a solution was proposed before, however the challenge of my minimum API requirements of 9 poses a problem.

推荐答案

您可以使用:

getActiveNetworkInfo();

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
}

这篇关于ConnectivityManager getNetworkInfo(int) 已弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 23:13