开发者

Trouble understanding CONNECTIVITY_ACTION extras

开发者 https://www.devze.com 2023-02-20 03:31 出处:网络
To be notified of network connections and disconnects, and to then know if my application can connect to the internet, I register a ConnectionManager.CONNECTIVITY_ACTION receiver. At present, I check

To be notified of network connections and disconnects, and to then know if my application can connect to the internet, I register a ConnectionManager.CONNECTIVITY_ACTION receiver. At present, I check if the phone has an active network connection like so:

if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
    // no connection!
} else {
    NetworkInfo activeNetInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
    if (activeNetInfo != null && activeNetInfo.isConnectedOrConnecting()) {
        // active connection!
    } else {
        // no connection!
    } 
}

However, I think I'm doing this wrong because my app can sometimes misreport the phone's connectivity status. Reading the documentation for EXTRA_NETWORK_INFO, it seems to indicate that if the value returned for this extra is null, then there is no connection: "...if the connectivity manager is attempting to connect (or has already connected) to another network, the NetworkInfo for the new network is also passed as an extra" (http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION).

However in instances where my app misreports connectivity, just prior to receiving the CONNECTIVITY_ACTION broadcast, getSystemService(Context.CONNE开发者_运维百科CTIVITY_SERVICE)).getActiveNetworkInfo() returns a NetworkInfo object whose isConnectedOrConnecting() check returns true. So the phone appears to be connected, but the NetworkInfo returned via the CONNECTIVITY_BROADCAST is null.

What am I doing wrong in my CONNECTIVITY_ACTION receiver code? Should I not check the value of EXTRA_NETWORK_INFO)? Can I simply rely on EXTRA_NO_CONNECTIVITY?

Any help is appreciated!


You're not doing anything wrong, but the only reliable value coming from isConnectedOrConnecting is false.

Even when the method returns true, you're not guaranteed that you'll be able to connect to the network.

When Android reports that you in fact have an active connection, you'll need to implement some kind of retry mechanism in case the connection doesn't seem to workable.

This can be the case for example when connecting to a corporate WIFI network, where all requests end up redirecting to the corporate login page. Android tells you that you have an active network, but your queries will obviously fail.

But even with a direct network connection, relying on it to return true is never a good idea without have some kind of retry mechanism in place for when things go wrong.

On the other hand, when the method returns false, you're guaranteed not to have a network connection.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号