在我的应用程序中,我需要实现某种聊天。但是我没有使用 longpoll 连接,而是get
每 5 秒向服务器发送一次请求。聊天不是我的应用程序中的主要功能。我Handler
用来发布一个Runnable
,run
我正在使用的方法AsyncHttpClient
。这是代码:
chatHandler = new Handler();
chatRunnable = new Runnable() {
@Override
public void run() {
final int pos = adapter.getCount();
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("X-Auth-token", User.getInstance(getApplicationContext()).getToken());
client.addHeader("clienttype", "android");
try {
client.addHeader("clientvesrion", (getPackageManager().getPackageInfo(getPackageName(), 0)).versionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
RequestParams params = new RequestParams();
params.add("todo_id", todo.getServerId() + "");
params.add("from_id", messages.size() == 0 ? "0" : messages.get(messages.size() - 1).getId() + "");
client.setTimeout(5000);
client.get(getApplicationContext(), getString(R.string.server_path) + getString(R.string.path_messages_from_id), params, new AsyncHttpResponseHandler(){
...
});
}
};
chatHandler.postDelayed(chatRunnable, 5000);
但是,有时这会崩溃并client.get()
出现以下错误:
FATAL EXCEPTION: main
java.lang.OutOfMemoryError: thread creation failed
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1050)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:913)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1295)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:81)
at com.loopj.android.http.AsyncHttpClient.sendRequest(AsyncHttpClient.java:893)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:612)
at ru.dotcapital.controlmanager.ChatActivity$1.run(ChatActivity.java:115)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
谷歌的一些参考说,当你有很多活动正在运行但尚未完成,并且有很多 AsyncTasks 一次运行,但我ChatActivity
是第 3 个活动时,它会发生。当错误出现时,用户会调用并且我没有及时运行 AsyncTasks。有什么建议么?