flender icon indicating copy to clipboard operation
flender copied to clipboard

Lollipop and WiFi Connectivity status changes

Open curioustechizen opened this issue 10 years ago • 2 comments

Great library! I've lost count of the amount of boilerplate I have written for precisely these kinds of connectivity checks.

One thing I have noticed is there is a problem with the way isNetworkConnected works in Lollipop and above. Referring to this code:.The issue is that if you have both WiFi and mobile data switched on, then all network data is transmitted on whatever whichever network has internet connection. For example, take this scenario:

  • Say, you have a local, non-internet connected WiFi device (like a Chromecast or other IoT device).
  • Your Android is connected to this WiFi Network.
  • Your mobile data is also on and that is connected to the internet

In this case, you will be told that you have WiFi connectivity, however if you make any HTTP requests etc, those will go over your mobile data. This may not be what you want. You might want to explicitly communicate with your Chromecast in this example.

The solution is to use the new APIs introduced in ConnectivityManager class in API 21 for this purpose - [requestNetwork](https://developer.android.com/reference/android/net/ConnectivityManager.html#requestNetwork%28android.net.NetworkRequest, android.net.ConnectivityManager.NetworkCallback%29) and setProcessDefaultNetwork.

More info here.

Having said all of that, I would understand if you do not want to support these complex use cases in this library since it is really meant to be a simple network check annotation lib!

curioustechizen avatar Jul 06 '15 05:07 curioustechizen

Thanks alot @curioustechizen for pointing this out. I am going to look into it. Would be great if you could submit the fix via a pull request though :+1:

jd-alexander avatar Jul 06 '15 23:07 jd-alexander

@jd-alexander The problem is the fix is non-trivial - as in - I can't think of an elegant way to make the API annotation-friendly. For starters, checking for network status is now an asynchronous, callback-based API. This snippet is taken straight from the M developer preview bug report but it is valid from Lollipop onwards:

ConnectivityManager cm = context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest request = new NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .build();
NetworkCallback callback = new NetworkCallback({
    @Override
    public void onAvailable(Network network) {
        // Either:
        cm.setProcessDefaultNetwork(network);  // L and above
        // or:
        cm.bindProcessToNetwork(network);      // M and above
        //At this point you are at a state equivalent to isConnectedWifi()
    }
});
cm.registerNetworkCallback(request, callback);

I'm not sure what the best way to handle this kind of code is.

curioustechizen avatar Jul 07 '15 11:07 curioustechizen