Access internet through mobile data when wifi is connected to OBD in marshmallow

647 views Asked by At

I have both WIFI and mobile data enabled. In wifi I have connected to an OBD which has no internet connection but will stream some data if connected. In order to start that stream I used the below code:

ConnectivityManager connectivityManager = (ConnectivityManager) getCurrentActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (SDK_INT >= LOLLIPOP) {
            NetworkRequest.Builder request = new NetworkRequest.Builder();
            request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);

            connectivityManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {

                @Override
                public void onAvailable(Network network) {
                    if (SDK_INT >= LOLLIPOP && SDK_INT < M) {
                        ConnectivityManager.setProcessDefaultNetwork(network);
                    } else if (SDK_INT >= M) {
                        connectivityManager.bindProcessToNetwork(network);
                    }
                }
            });
        }

I got the code from this answer.

How to stay connected through mobile network after WIFI is connected on Android?

When it comes to get the active network into at connectivityManager.getActiveNetworkInfo() I get the network type as MOBILE[LTE]. Once it hits the onAvailable method, whenever I try to get the active network type it says WIFI[].

After this the stream gets started. Now I want the mobile data to be activated again since it is enabled. So I tried the same code after the stream started by just replacing TRANSPORT_WIFI with TRANSPORT_CELLULAR in request.addTransportType.

ConnectivityManager connectivityManager = (ConnectivityManager) getCurrentActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (SDK_INT >= LOLLIPOP) {
            NetworkRequest.Builder request = new NetworkRequest.Builder();
            request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

            connectivityManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {

                @Override
                public void onAvailable(Network network) {
                    if (SDK_INT >= LOLLIPOP && SDK_INT < M) {
                        ConnectivityManager.setProcessDefaultNetwork(network);
                    } else if (SDK_INT >= M) {
                        connectivityManager.bindProcessToNetwork(network);
                    }
                }
            });
        }

What happens is, when I debug this process, NetworkInfo always has the WIFI connection even after it hits the onAvailable method.

Please pinpoint if I was wrong somewhere or am I missing something.

0

There are 0 answers