gpt4 book ai didi

java - 异步任务不是异步的

转载 作者:行者123 更新时间:2023-12-01 16:33:27 26 4
gpt4 key购买 nike

我正在 Android 中开发一个聊天应用程序,但遇到了一个大问题。我需要一个线程在后台不断运行(轮询服务器),并通过句柄将其附加到我的主进程。

主要问题是:只要这个后台线程在运行,前台线程就会完全停止!

这是一段不完整的代码(因为完整版本更长/更丑)...

public class ChatActivity extends Activity {
...

private Thread chatUpdateTask;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);

...

chatUpdateTask = new ChatUpdateTask(handler);
chatUpdateTask.start();
}

public void updateChat(JSONObject json) {
// ...
// Updates the chat display
}


// Define the Handler that receives messages from the thread and update the progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// Get json from the sent Message and display it
updateChat(json);
}
};

public class ChatUpdateTask extends Thread {
Handler mHandler; // for handling things outside of the thread.

public ChatUpdateTask(Handler h) {
mHandler = h; // When creating, make sure we request one!
}//myTask

@Override
public void start() {
while(mState==STATE_RUNNING) {

// ...
// Send message to handler here

Thread.sleep(500); // pause on completion

}//wend
}//end start

/* sets the current state for the thread,
* used to stop the thread */
public void setState(int state) {
mState = state;
}//end setState


public JSONObject getChatMessages() {
// ... call server, return messages (could take up to 50 seconds to execute;
// server only returns messages when there are new ones
return json;
}
}//end class myTask


}

最佳答案

您正在重写start()。线程在其 run() 方法中运行。

http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

关于java - 异步任务不是异步的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11990043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com