Android - ConnectivityManager.EXTRA_NETWORK_INFO 已弃用

Android - ConnectivityManager.EXTRA_NETWORK_INFO deprecated

我正在创建 BroadcastReceiver 来侦听 Wi-Fi 连接变化:[​​=15=]

registerReceiver(new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {

            NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); // deprecated

            // Get connectivity details from networkInfo...

        }

    }

}, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

但是,ConnectivityManager.EXTRA_NETWORK_INFO 已被弃用,那么如何获取 NetworkInfo 对象呢?

您可以使用 getActiveNetworkInfo();

ConnectivityManager connectivityManager = (ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();