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
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.
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.
Is the service getting stopped somehow?
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.
精彩评论