每当有人点击我的Firebase聊天室应用程序中的发送按钮时,我都会尝试发送HTTP请求。该请求与 Firebase 无关。但对于其中的某些功能很重要。
每次我点击发送按钮时,我的应用程序都会滞后一点。此外,每次我在发送此 http 请求之前先调用 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类进行测试,但我遇到了同样的滞后或冻结问题。我做错了什么?:(
您正在使用 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
}
});
您可以尝试将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>