Android volley doesn't work on local WiFi if 3G/4G is ON

霸气de小男生 提交于 2021-02-11 12:35:11

问题


I have an app that communicates with a Ricoh Theta camera. The camera creates its WiFi network and OSC (Open Spherical Camera) web server (IP 192.168.1.1, port 80), on which I connect my device. Everything works fine if only the WiFi is ON. But when I also put the mobile data ON, then I get a timeout error.

No sure if it can be useful, but here is some code:

protected void executePost(String request, final String body, final RequestListener listener) {

    StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://" + mIpAddress + ":" + mPort + request,

            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    if(listener != null) {
                        handleResponse(response, listener);
                    }
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    if(listener != null) {
                        listener.onError(error);
                    }
                }
            }
    )
    {
        @Override
        public byte[] getBody() throws AuthFailureError {

            return body == null ? null : body.getBytes();
        }
    };

    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);

    stringRequest.setTag(REQUEST_TAG);
    mRequestQueue.add(stringRequest);
}

Is there a way to tell Volley to use the WiFi only? Or first?


回答1:


OK, sorry, after some research I found the solution, here: https://code.google.com/p/android/issues/detail?id=190974

The problem is that as of Android 6.0, if the device is connected to several networks, Android will connect to the one with an internet access, and ignore the other(s). Seems pretty weird, to be polite, but still...

Here is the code I added to make it working:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {

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

    for (Network net : connectivityManager.getAllNetworks()) {

        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(net);

        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            connectivityManager.bindProcessToNetwork(net);
            break;
        }
    }
}


来源:https://stackoverflow.com/questions/39611338/android-volley-doesnt-work-on-local-wifi-if-3g-4g-is-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!