Android 服务中的数据包监听器
我正在尝试使用 XMPP 为聊天小部件创建一项服务,该服务会在发送给用户时拾取聊天消息。
我创建了一个服务,在 onStart 中我使用 AsyncTask 连接到聊天服务器,然后设置一个数据包侦听器。
这是加壳监听器的代码:
public void setConnection(XMPPConnection connection) {
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.v(TAG, "Got:" + message.getBody());
// messages.add(fromName + ":");
// messages.add(message.getBody());
}
}
}, filter);
}
}
问题是它似乎在空闲一段时间后停止监听。如果我立即发送聊天消息,它们就会得到输出。
服务是否以某种方式停止了?这是放置 packerlistener 的正确位置吗?
谢谢
I am trying to create a service for a chat widget using XMPP, which picks up chat messages when they are sent to the user.
I have created a service, and in the onStart I use a AsyncTask to connect to the chat server, and then sets up a packetlistener.
Here's the code for the packer listener:
public void setConnection(XMPPConnection connection) {
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.v(TAG, "Got:" + message.getBody());
// messages.add(fromName + ":");
// messages.add(message.getBody());
}
}
}, filter);
}
}
The problem is it seems to stop listening after being idle for a while. If I send chat messages straight away they get output.
Is the service getting stopped somehow? Is that the right place to put the packerlistener?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不建议这样做。创建您自己的线程,而不是
AsyncTask
。AsyncTask
是为那些将在毫秒或秒内结束的事情而设计的,而不是分钟或小时。很有可能。使用
adb logcat
、DDMS 或 Eclipse 中的 DDMS 透视图来检查 LogCat 并查看它告诉您有关代码的信息。您应该在服务中使用
startForeground()
,特别是当您计划在聊天客户端活动不一定位于前台时保持服务运行时。I do not recommend that. Create your own thread, not an
AsyncTask
.AsyncTask
is designed for things that will end in milliseconds or seconds, not minutes or hours.Quite possibly. Use
adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine LogCat and see what it tells you about your code.You should be using
startForeground()
in your service, particularly if you plan on keeping the service running when your chat client activity is not necessarily in the foreground.