Difference between registerDefaultNetworkCallback and registerNetworkCallback

后端 未结 6 1948
不知归路
不知归路 2021-01-01 18:30

I came across registerDefaultNetworkCallback and registerNetworkCallback while updating my Android app for API 28.

Having reviewed the documentation, I cannot find t

6条回答
  •  时光说笑
    2021-01-01 19:23

    Most of these answers are more or less correct. That said, what I can add is that default network has a particular meaning in Android hence the difference in naming. The default network pertains to whichever network is chosen as the "best" device wide network. This network will be used by default for any connectivity requests.

    If you are using a phone and only have a Cellular connection available, that will be the default network. As soon as you connect to Wi-Fi however that will become the default network as it is considered the "best" network and all connectivity requests which don't specify anything different will now use it by default whether they realize it or not. This is because Wi-Fi is considered better then Cellular as long as Wi-Fi has NetworkCapability.NET_CAPABILITY_NOT_METERED. Now if it turns out that the Wi-Fi network is in fact a metered network while cellular isn't, then the default network would switch back to cellular.

    Therefore when you use registerDefaultNetworkCallback(), what you are really saying is let me know about changes that occur on the network tagged as the "best" network on the device that all apps will use by default unless they request something different. This is why you don't need to pass a NetworkCapability as part of the registration since the default network is controlled by the framework.

    registerNetworkCallback() is similar except that it doesn't care about the default network. You give it some NetworkCapability and you track on any networks that satisfy those network capabilities regardless of whether they are the default or not.

    You can see more by looking at getDefaultNetwork() in ConnectivityService.

提交回复
热议问题