8

我不明白为什么在随机时刻多次调用onAvailable,文档说明如果网络发生变化可以调用更多,但onAvailable中网络对象参数的属性始终相同。我什至比较了哈希码,它们是相同的......

问题出现在我的 LG 棒棒糖设备上

Android 文档:(https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback

onAvailable 在 API 级别 21 中添加,当框架连接并声明一个新网络可供使用时调用。如果满足请求的网络发生变化,可能会多次调用此回调

编辑:我已经从回调中实现了其他方法,以检查是否触发了任何其他方法(onLosing、onUnavailable、onCapabilitiesChanged、onLinkPropertiesChanged),但这些方法都没有被调用

我有自己的 NetworkManager,其中包含以下代码:

public void initialize(Context context) {
    connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    setState();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        final NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();

        connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(final Network network) {
                super.onAvailable(network);
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                Log.d(TAG,"Network is Available. Network Info: " + networkInfo);
                notifyObservers();
            }

            @Override
            public void onLost(final Network network) {
                super.onLost(network);
                notifyObservers();
            }
        });
    } else {
        context.registerReceiver(new NetworkChangeReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
}

日志:

Network is Available. Network Info: [type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "company_guest", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false]
Network is Available. Network Info: [type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "company_guest", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false]
Network is Available. Network Info: [type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "company_guest", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false]
Network is Available. Network Info: [type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "company_guest", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false]
...
4

0 回答 0