Android:在运行蓝牙发现的情况下,HttpURLConnection 确实需要很长时间才能获得响应

发布于 2025-01-06 23:46:38 字数 5442 浏览 0 评论 0原文

我正在开发一个应用程序,它连接到排名服务器,以获取当前排名。

为此,我使用 HttpURLConnection 类。 我的问题是,尽管我是通过 WiFi 连接的,但连接时间却很长。有时连接也会拒绝。然后我就不再与 WiFi 路由器连接了。 服务器速度快,网络连接良好,延迟小。 出于测试目的,我计算了每个部分之间的时间。

这是代码:

        //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;

当我连接到 WiFi 并重新连接到它时,启动应用程序,连接时间应该是这样:

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

但是当我关闭应用程序并再次打开它时,连接时间太长:

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

所以我的问题是,为什么只有 11 个字符才响应 30 秒? 当平板电脑距离 WiFi 路由器 5 厘米时,也会出现此问题。

在其他应用程序中不会出现此问题,仅在本应用程序中出现此问题。

我无法通过 3G 检查。

你能帮助我吗 ?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℡Ms空城旧梦 2025-01-13 23:46:38

好吧,我知道问题所在了。

经过长时间的搜索,我发现了一些有趣的事情。

如果您的设备已连接到 WiFi 并且当前正在发现蓝牙设备,则信号之间存在很多干扰!当WiFi和蓝牙都在接收或发送数据时,蓝牙信号会干扰WiFi,导致WiFi信号下降或持续时间异常长。因此,如果您想从 WiFi 网络检索数据,请确保没有蓝牙发现或传输正在运行。

要检查是否已连接到 WiFi,您可以使用以下代码:

    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;
            }   

        }
    }

然后在 AsyncTaskonPreExecute() 方法中,您应该检查是否已连接到 WiFi 并取消当前发现

BluetoothAdapter.cancelDiscovery();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文