networkinfo和wificonfiguration在sdk 22中已被弃用

guz6ccqo  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(1057)

我在pax a920设备(sdk版本22)中使用android棒棒糖。生成时,我收到如下警告消息:
NetworkInfo in android.net has been deprecated WifiConfiguration in android.net has been deprecated 我很困惑,因为我在中看到了sdk 22的示例 C:\Users\{YOUR_ACCOUNT}\AppData\Local\Android\Sdk\sources\android-22\com\android\connectivitymanagertest 使用该方法访问wifi,但为什么它看起来不受欢迎?
什么方法与替换不推荐的方法相同?

public boolean isWifiConnected() {
    boolean isWifiConnected = false;
    try {
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo != null) {
            isWifiConnected = networkInfo.getState() == CONNECTED;
        }
        Log.i(TAG, "wifi adapter is connected? " + isWifiConnected);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return isWifiConnected;
}

public void removeNetwork() {
    List<WifiConfiguration> wifiCfgList = wifiManager.getConfiguredNetworks();
    if (wifiCfgList.size() > 0) {
        for (WifiConfiguration item : wifiCfgList) {
            if (item != null) {
                wifiManager.removeNetwork(item.networkId);
                wifiManager.saveConfiguration();
            }
        }
    }
}

谢谢你的指点。

z9ju0rcb

z9ju0rcb1#

欢迎来到stackoverflow!
不推荐使用的类已使用 ConnectivityManager 系统服务和 NetworkCallbacks : https://developer.android.com/training/monitoring-device-state/connectivity-status-type
尽管官方代码示例演示了如何获取 NetworkInfo 从…起 ConnectivityManager 有一个突出显示的注解:

下面是一个示例代码,说明如何获取当前网络状态,以及如何随着时间的推移接收更新。这是一个部分精简的解决方案,我将在生产中使用。如果将其与rxjava或rxkotlin连接,则可以创建一个可观察对象,该对象将保存网络状态,并在调用networkcallback的重写方法时进行更新。
关于java的注意事项:公共类级别的变量是为了简洁而公开的。相反,我会为这些变量创建一些getter来访问这些变量背后的值。
请随意提问。
JAVA

class NetworkReachabilityService {

    public NetworkType networkType;
    public NetworkState networkState = NetworkState.Unavailable;
    private ConnectivityManager connectivityManager;
    private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);
            updateAvailability(connectivityManager.getNetworkCapabilities(network));
        }

        @Override
        public void onLosing(@NonNull Network network, int maxMsToLive) {
            super.onLosing(network, maxMsToLive);
            networkState = NetworkState.Losing;
        }

        @Override
        public void onLost(@NonNull Network network) {
            super.onLost(network);
            networkState = NetworkState.Lost;
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            networkState = NetworkState.Unavailable;
        }

        @Override
        public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            updateAvailability(networkCapabilities);
        }
    };

    public NetworkReachabilityService(Context context) {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    private void updateAvailability(NetworkCapabilities networkCapabilities) {
        if (networkCapabilities == null) {
            networkState = NetworkState.Unavailable;
            return;
        }

        if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            networkType = NetworkType.CELL;
        } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            networkType = NetworkType.WiFi;
        }

        networkState = NetworkState.Available;
    }

    public void resumeListeningNetworkChanges() {
        pauseListeningNetworkChanges();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(networkCallback);
        } else {
            connectivityManager.registerNetworkCallback(
                    new NetworkRequest.Builder().build(),
                    networkCallback
            );
        }
    }

    public void pauseListeningNetworkChanges() {
        try {
            connectivityManager.unregisterNetworkCallback(networkCallback);
        } catch (IllegalArgumentException exception) {
            // Usually happens only once if: "NetworkCallback was not registered"
        }
    }

    private enum NetworkState {
        Available, Unavailable, Connecting, Losing, Lost
    }

    private enum NetworkType {
        WiFi, CELL, OTHER
    }
}

Kotlin

sealed class NetworkState {
    data class Available(val type: NetworkType) : NetworkState()
    object Unavailable : NetworkState()
    object Connecting : NetworkState()
    object Losing : NetworkState()
    object Lost : NetworkState()
}

sealed class NetworkType {
    object WiFi : NetworkType()
    object CELL : NetworkType()
    object OTHER : NetworkType()
}

class NetworkReachabilityService private constructor(context: Context) {

    private val connectivityManager: ConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    private val networkCallback = object : ConnectivityManager.NetworkCallback() {
        // There are more functions to override!

        override fun onLost(network: Network) {
            super.onLost(network)
            networkState = NetworkState.Lost
        }

        override fun onUnavailable() {
            super.onUnavailable()
            networkState = NetworkState.Unavailable
        }

        override fun onLosing(network: Network, maxMsToLive: Int) {
            super.onLosing(network, maxMsToLive)
            networkState = NetworkState.Losing
        }

        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            updateAvailability(connectivityManager.getNetworkCapabilities(network))
        }

        override fun onCapabilitiesChanged(
            network: Network,
            networkCapabilities: NetworkCapabilities
        ) {
            super.onCapabilitiesChanged(network, networkCapabilities)
            updateAvailability(networkCapabilities)
        }
    }

    var networkState: NetworkState = NetworkState.Unavailable
        private set

    private fun updateAvailability(networkCapabilities: NetworkCapabilities?) {
        if (networkCapabilities == null) {
            networkState = NetworkState.Unavailable
            return
        }
        var networkType: NetworkType = NetworkType.OTHER

        if (networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
            networkType = NetworkType.CELL
        }
        if (networkCapabilities.hasTransport(TRANSPORT_WIFI)) {
            networkType = NetworkType.WiFi
        }

        networkState = NetworkState.Available(networkType)
    }

    fun pauseListeningNetworkChanges() {
        try {
            connectivityManager.unregisterNetworkCallback(networkCallback)
        } catch (e: IllegalArgumentException) {
            // Usually happens only once if: "NetworkCallback was not registered"
        }
    }

    fun resumeListeningNetworkChanges() {
        pauseListeningNetworkChanges()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(networkCallback)
        } else {
            connectivityManager.registerNetworkCallback(
                NetworkRequest.Builder().build(),
                networkCallback
            )
        }
    }
}

开始接收网络状态更新呼叫 resumeListeningNetworkChanges 停止 pauseListeningNetworkChanges 分别地

相关问题