Search code examples
androidwifiresponselong-integerhttpurlconnection

Android: HttpURLConnection does take very long to get the response with Bluetooth discovery running


I'm developing an app, that connects to a ranking server, to get the current rank.

For this I'm using the HttpURLConnection class. My problem is, that I'm getting very long connection times, although I'm connected via WiFi. Sometimes the connection also refuses. Then I'm no more connected with the WiFi router. The server is fast and has a good network connection and latency. For testing purposes I calculated the time between each part.

Here is the code:

        //The code runs in the doInBackground(String... params) method

        long randStartTime = System.currentTimeMillis();

        do
        {
            Random randomGenerator = new Random();
            randomgen = randomGenerator.nextInt(10);
        }while(randomgen == 0);

        int random = //Calculation of the Session_ID
        String res = null;

        long randEndTime = System.currentTimeMillis();
        Log.d("RandEXETime", String.valueOf(randEndTime - randStartTime));

        HttpURLConnection connection = null;


        try {        

            long URLStartTime = System.currentTimeMillis();


            String[] paramsList = params[0].split("\n");
            Log.d("SMBD_AsyncTask_params", paramsList[0] + "|" + paramsList[1] + "|" + paramsList[2] + "|" + paramsList[3]);
            Integer idList = Integer.decode(paramsList[0]);

            String request;

            if(idList == 0) {
                request = "http://maks.mph-p.de/blue/checkrankv12.php?device_number=" + paramsList[3] + "&session_id=" + random;
            }else{

                Log.d("SMBD ID", idList.toString());
                request = "http://maks.mph-p.de/blue/checkrankv12.php?read=1&id=" + idList + "&device_number=" + paramsList[3] + "&session_id=" + random;

            }

            String urlParameters = "adress=" + URLEncoder.encode(paramsList[1], "UTF-8") + "&name=" + URLEncoder.encode(paramsList[2], "UTF-8");

            URL url = new URL(request); 

            long URLEndTime = System.currentTimeMillis();           
            Log.d("URLEXETime", String.valueOf(URLEndTime - URLStartTime));



            long RequestStartTime = System.currentTimeMillis();

            connection = (HttpURLConnection) url.openConnection();           
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST"); 
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setUseCaches (false);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            long RequestEndTime = System.currentTimeMillis();           
            Log.d("RequestEXETime", String.valueOf(RequestEndTime - RequestStartTime));

            Log.d("SMBD_AsynkTask", "After sending");

            long ResponseStartTime = System.currentTimeMillis();


                InputStream in = new BufferedInputStream(connection.getInputStream());

            long ResponseEndTime = System.currentTimeMillis();              
            Log.d("ResponseEXETime", String.valueOf(ResponseEndTime - ResponseStartTime));

            long ResponseINStartTime = System.currentTimeMillis();

                res = inputStreamToString(in);

                long ResponseINEndTime = System.currentTimeMillis();            
                Log.d("ResponseINEXETime", String.valueOf(ResponseINEndTime - ResponseINStartTime));    


            Log.d("SMBD_AsynkTask_response", res);

            //}
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block

            res = "false";
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block

            res = "false";
        }catch (IOException e2) {
            // TODO Auto-generated catch block

            res = "false";
        }finally{
            connection.disconnect();
        }




        String result = res;
        return result;

When I'm connected to WiFi and reconnect to it, start the app, the connection time is like it should be:

02-17 15:21:27.800: D/RandEXETime(6008): 0
02-17 15:21:27.800: D/SMBD_AsyncTask_params(6008): 4454|C8:AA:21:F1:C0:BA|Maksl5|57
02-17 15:21:27.800: D/SMBD ID(6008): 4454
02-17 15:21:27.800: D/URLEXETime(6008): 1
02-17 15:21:27.870: D/RequestEXETime(6008): 68
02-17 15:21:27.870: D/SMBD_AsynkTask(6008): After sending
02-17 15:21:27.950: D/ResponseEXETime(6008): 76
02-17 15:21:27.950: D/ResponseINEXETime(6008): 1
02-17 15:21:27.950: D/SMBD_AsynkTask_response(6008): 101. / 2171

But when I close the app and open it again, the connection time is too long:

02-17 15:06:36.220: D/RandEXETime(5575): 0
02-17 15:06:36.220: D/SMBD_AsyncTask_params(5575): 4454|C8:AA:21:F1:C0:BA|Maksl5|56
02-17 15:06:36.220: D/SMBD ID(5575): 4454
02-17 15:06:36.220: D/URLEXETime(5575): 2
02-17 15:06:39.300: D/RequestEXETime(5575): 3070
02-17 15:06:39.300: D/SMBD_AsynkTask(5575): After sending
02-17 15:06:45.490: D/dalvikvm(5575): GC_CONCURRENT freed 192K, 4% free 6755K/6983K, paused 2ms+2ms
02-17 15:07:09.130: D/ResponseEXETime(5575): 29830
02-17 15:21:56.430: D/ResponseINEXETime(6008): 1
02-17 15:07:09.130: D/SMBD_AsynkTask_response(5575): 102. / 2171

So my question is, why does the response take 30 seconds for only 11 characters ? The problem also occurs, when the tablet is 5 cm near the WiFi router.

The problem does not occur in other apps, only in this app.

I can not check it via 3G.

Can you help me ?


Solution

  • Ok, I know the problem.

    After long searching, I found some interesting things.

    If your device is connected to WiFi AND currently is discovering Bluetooth devices, there are much interferences between the signals ! In the case both, WiFi and Bluetooth are retrieving or sending data, the Bluetooth signal interferes the WiFi and so the WiFi signal drops or lasts unnormaly long. So be sure if you want to retrieve data from a WiFi network, that no Bluetooth discoveries or transfers are running.

    To check if connected to WiFi you can take this code:

        boolean IsConnectedToWifi = false;
    
        ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInf = conMgr.getAllNetworkInfo();
        for(NetworkInfo inf : netInf){
            if(inf.getTypeName().contains("WIFI"))
            {
                if(inf.isConnected()){
                    IsConnectedToWifi = true;
                }   
    
            }
        }
    

    Then in the onPreExecute() method in your AsyncTask you should check, if connected to WiFi and cancel the current discovery with

    BluetoothAdapter.cancelDiscovery();