【问题标题】:Android app lags while making a HTTP url connection建立 HTTP url 连接时 Android 应用程序滞后
【发布时间】:2019-10-04 08:25:38
【问题描述】:

每次有人点击我的 firebase 聊天室应用中的发送按钮时,我都会尝试发送 HTTP 请求。该请求与 Firebase 无关。但对于其中的某些功能很重要。

每次我点击发送按钮时,我的应用都会有点滞后。此外,每次我在发送此 http 请求之前先调用 Firebase 函数时,我的应用程序都会完全冻结...

只调用 Firebase 超级流畅...

我还想通过 http 连接将打字信号发送到不同的服务器。但由于这种滞后,这几乎是不可能的......

这是我的代码,

   public static String post(URL url, String data) throws IOException {
        StringBuilder out = new StringBuilder();
        final CountDownLatch latch = new CountDownLatch(1);

        Thread httpThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("User-Agent", userAgent);
                    conn.setDoOutput(true);

                    OutputStreamWriter writer = new OutputStreamWriter(
                            conn.getOutputStream());
                    writer.write(data);
                    writer.flush();


                    String line;

                    BufferedReader input = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
                    try {
                        while ((line = input.readLine()) != null) {
                            out.append(line).append("\n");
                        }
                    } finally {
                        input.close();
                    }
                    latch.countDown();

                } catch (Exception e) {

                }


            }

        });
        httpThread.start();
        try {
            latch.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Sending Output : "+out);
        return out.toString().trim();


    }

另外,我尝试使用特定的 AsyncTask 类进行测试,但我遇到了同样的延迟或冻结问题。我究竟做错了什么? :(

【问题讨论】:

    标签: java android android-asynctask httpconnection


    【解决方案1】:

    您正在使用 HTTP 线程,但最终,您正在等待线程在您的主 UI 线程中完成,这会阻塞和滞后应用程序。

    您可以使用 android-async-http 库来帮助发送异步(非阻塞)请求:

    https://loopj.com/android-async-http/

    在你的 gradle 构建文件中添加这一行:

    implementation 'com.loopj.android:android-async-http:1.4.9'
    

    使用示例:

    import com.loopj.android.http.*;
    
    AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://www.google.com", new AsyncHttpResponseHandler() {
    
        @Override
        public void onStart() {
            // called before request is started
        }
    
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
        }
    
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        }
    
        @Override
        public void onRetry(int retryNo) {
            // called when request is retried
        }
    });
    

    【讨论】:

    • 感谢您的回答。我尝试在 Asynchttpclient 上发出类似的请求。但我不断收到错误的请求错误。您能否查看此代码pastebin.com/index/PdXHZBUp
    • 能否提供更多关于您的错误的详细信息,例如屏幕截图、日志等。
    【解决方案2】:

    您可以尝试将usesCleartextTraffic 添加到AndroidManifest.xml 文件中

    <application
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"/>
    </application>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      相关资源
      最近更新 更多