Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request over wifi on Android M

I'm currently developping an app on Android and I got problem since Android 6.0 update : I'm unable to request over my private network !

ex : Step 1 : Connect to a wifi which doesn't provide an internet connection Step 2 : Make a request (ex : POST request) on a local ip (ex: 192.168.1.168)

On any Android version (except 6.0) : I got a response from my local web server On android M : no response : my request goes over mobile data.

When I turn off my mobile data, the request goes over wifi and I got correct answers. Tell me if I'm wrong but apparently I can't solve my problem in app by turning off data programatically or forcing wifi use with api 23...

like image 501
Guillaume Hugot Avatar asked Oct 20 '15 12:10

Guillaume Hugot


1 Answers

Here is how I solved my problem if anyone is interested :

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network activeNetwork = connectivityManager.getActiveNetwork();
        if (WifiConnectionManager.getInstance(mCtx).isConnectedToALocalWifi()) {
            for (Network net : connectivityManager.getAllNetworks()) {
                if (!net.equals(activeNetwork)) {
                    connectivityManager.bindProcessToNetwork(net);
                    try {
                        net.openConnection(new URL(mCtx.getString(R.string.wifi_cam_url)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

}

Have fun !

like image 51
Guillaume Hugot Avatar answered Oct 04 '22 08:10

Guillaume Hugot