我是安卓系统的新手。在我当前的项目中,我使用asmack库来接收XMPP消息。在我的主要活动中,我有:
Connection connection; // from the asmack library
和
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
// HERE! is where I want to update the UI when I receive packets
}
}
奇怪的是,当我解析数据包并简单地在两个标签上调用setText()时。起初什么都没发生,但当我触摸按钮(因此调用一些更新例程)时,只有第一个标签被更新。
现在,据我所知,在这种情况下应该使用AsyncTask,但这也没有成功。
我是否误解了一些核心概念?有人能带领我走上正确的道路吗?
数据包似乎是在一个独立于UI线程的线程上处理的,这意味着UI不会立即更新,因为您没有在它的线程上操作它。因此,你应该这样做。。。
connection.addPacketListener(new PacketListener(){
public void processPacket(Packet packet){
//update the UI on its thread
runOnUiThread(new Runnable()){
public void run(){
//update UI elements
}
}
}
}