3
votes

I own a diagnostic device that also acts as a Wifi access point. Any device can connect to that access point and request information from the device. The device obviously does not provide internet access over that network.

I tried to create an android app that requests information from the device, using the provided Wifi network, and then uploads the data to some server in the internet using the cellular connection.

Android, however, seems to deactivate the cellular connection whenever a Wifi network is connected. Since the Wifi network is not connected to the internet, the data cannot be uploaded, and the app is useless.

So far I tried to use the ConnectivityManager to request the mobile network and bind it to my communication socket. Also, I tried to iterate all network interfaces and bind the communication socket to the IP address of the cellular interface. However, both requests failed since I was not able to query the cellular network interface from the app.

How could I manage to forward the data from the device in the Wifi network to some server over the cellular internet connection?

2

2 Answers

1
votes

I filed a bug report for this issue.

The issue should be fixed in Android version 5.1.0

0
votes

Here is the right sample code.

NetworkRequest cellularRequest = new NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
if (connectivityManager != null) {
    connectivityManager.requestNetwork(cellularRequest, new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);
            // do request with the network
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.socketFactory(network.getSocketFactory());
            OkHttpClient client = builder.build();
            Call call = client.newCall(request);
            Response response = call.execute();

            // do remove callback. if you forget to remove it, you will received callback when cellular connect again.
            connectivityManager.unregisterNetworkCallback(this);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            // do remove callback
            connectivityManager.unregisterNetworkCallback(this);
        }
    });
}