基本上我在我的应用程序中实现聊天功能。我正在使用计时器类来获取发件人的消息。这里是代码Timer timer = new Timer();
TimerTask getMessagesTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
try {
newMessages = connectToserverforincomingmsgs(
getmsgurl, number);
if (newMessages.length() > 0)
{
TextView tv = new TextView(Chat.this);
tv.setText(number + ":" + newMessages);
LayoutParams param = new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
tv.setLayoutParams(param);
((LinearLayout) findViewById(R.id.ll_chat))
.addView(tv);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(getMessagesTask, 3000, 3000);
}
每隔3秒对服务器进行一次ping操作,检查用户是否收到了新消息。但是,不仅对用户而且对我而言,它确实很昂贵。请为此建议最好的解决方案